use*_*425 7 closures move-semantics rust
我试图将一个闭包传递给一个函数,然后该函数将在函数范围内改变传递给它的东西.根据我目前对Rust的理解,这应该是这样的:
pub fn call_something(callback: &FnOnce(&mut Vec<i32>)) {
let mut my_vec = vec![0, 1, 2, 3, 4];
callback(&mut my_vec);
}
Run Code Online (Sandbox Code Playgroud)
这导致了这些错误:
error[E0161]: cannot move a value of type dyn for<'r> std::ops::FnOnce(&'r mut std::vec::Vec<i32>): the size of dyn for<'r> std::ops::FnOnce(&'r mut std::vec::Vec<i32>) cannot be statically determined
--> src/lib.rs:3:5
|
3 | callback(&mut my_vec);
| ^^^^^^^^
error[E0507]: cannot move out of borrowed content
--> src/lib.rs:3:5
|
3 | callback(&mut my_vec);
| ^^^^^^^^ cannot move out of borrowed content
Run Code Online (Sandbox Code Playgroud)
为什么要FnOnce采取行动?我在这里错过了什么?
为什么要
FnOnce采取行动?
extern "rust-call" fn call_once(self, args: Args) -> Self::Output
// ^^^^
Run Code Online (Sandbox Code Playgroud)
extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output
// ^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
extern "rust-call" fn call(&self, args: Args) -> Self::Output
// ^^^^^
Run Code Online (Sandbox Code Playgroud)
也可以看看:
你可能想要
pub fn call_something(callback: impl FnOnce(&mut Vec<i32>))
Run Code Online (Sandbox Code Playgroud)
要么
pub fn call_something<F>(callback: F)
where
F: FnOnce(&mut Vec<i32>),
Run Code Online (Sandbox Code Playgroud)
这些是相同的.它们都拥有闭包的所有权,这意味着你可以调用闭包并在过程中使用它.