首页 > 解决方案 > 为什么调用 FnOnce 闭包是一个举动?

问题描述

我试图将一个闭包传递给一个函数,该函数将在函数范围内改变传递给它的东西。根据我目前对 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一个动作?我在这里想念什么?

标签: rustclosuresmove-semantics

解决方案


为什么叫FnOnce一个动作?

因为这就是闭包定义FnOnce

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

FnMut将此与和进行对比Fn

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>),

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


推荐阅读