rust - 为什么调用 FnOnce 关闭是一个 Action ?

标签 rust closures move-semantics

我正在尝试将一个闭包传递给一个函数,该函数随后会在该函数的范围内改变传递给它的某些内容。根据我目前对 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
//                              ^^^^

对比 FnMutFn :

extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output
//                             ^^^^^^^^^
extern "rust-call" fn call(&self, args: Args) -> Self::Output
//                         ^^^^^

另见:


你可能想要

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/

相关文章:

rust - 如何帮助类型推断系统推断闭包参数的类型?

C++:使用整数 move 语义

c++ - 使用 move 构造函数

rust - proc_macro_attribute 函数内部是否存在一致的编译上下文?

rust - 使用 if let 时如何指定无法推断的类型?

rust - 如何在 Rust 中创建一个引用 trait 实现的静态数组?

Swift 4.2 闭包

objective-c - 在 Swift 2.1 中使用在 Objective C 中声明为 block 的闭包 Swift

javascript - 从闭包中取回数据

reference - 无法移出借用的内容/无法移出共享引用