我正在尝试将一个闭包传递给一个函数,该函数随后会在该函数的范围内改变传递给它的某些内容。根据我目前对 Rust 的理解,它应该看起来像这样:
pub fn call_something(callback: &FnOnce(&mut Vec<i32>)) {
let mut my_vec = vec![0, 1, 2, 3, 4];
callback(&mut my_vec);
}
这会导致这些错误:
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
为什么调用 FnOnce
是一个 Action ?我在这里缺少什么?
最佳答案
Why is calling a
FnOnce
a move?
因为那是 the definition of what makes a closure FnOnce
:
extern "rust-call" fn call_once(self, args: Args) -> Self::Output
// ^^^^
extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output
// ^^^^^^^^^
extern "rust-call" fn call(&self, args: Args) -> Self::Output
// ^^^^^
另见:
- When does a closure implement Fn, FnMut and FnOnce?
- "cannot move a value of type FnOnce" when moving a boxed function
- Cannot move out of borrowed content
你可能想要
pub fn call_something(callback: impl FnOnce(&mut Vec<i32>))
或
pub fn call_something<F>(callback: F)
where
F: FnOnce(&mut Vec<i32>),
这些是相同的。它们都拥有闭包的所有权,这意味着您可以调用闭包并在流程中使用它。
关于rust - 为什么调用 FnOnce 关闭是一个 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53233803/