【问题标题】:Why is calling a FnOnce closure a move?为什么调用 FnOnce 闭包是一个举动?
【发布时间】:2019-04-13 12:00:03
【问题描述】:

我正在尝试将一个闭包传递给一个函数,该函数将在函数范围内改变传递给它的某些内容。根据我目前对 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 是一个举动?我在这里错过了什么?

【问题讨论】:

    标签: rust closures move-semantics


    【解决方案1】:

    为什么调用FnOnce 是一个动作?

    因为那是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>),
    

    这些是相同的。它们都拥有闭包的所有权,这意味着您可以调用闭包并在进程中使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多