rust - 为什么调用 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
一个动作?我在这里想念什么?
解决方案
为什么叫
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
// ^^^^^
也可以看看:
你可能想要
pub fn call_something(callback: impl FnOnce(&mut Vec<i32>))
或者
pub fn call_something<F>(callback: F)
where
F: FnOnce(&mut Vec<i32>),
这些是相同的。它们都拥有闭包的所有权,这意味着您可以调用闭包并在流程中使用它。
推荐阅读
- c++ - 难以从 c++ boost 库中获取 barycentric_rational 以按照我的需要工作
- c# - Visual Studio 代码 - 参考文件夹
- macos - 在 PlaidML 中使用实验设备支持?
- java - 如何防止删除液
- python-3.x - Groupby 与 Cumcount - 未按预期工作
- python - 基于数据库引擎的 Alembic 条件
- python - 等价于Python对R中字符串的综合列表操作
- environment-variables - 获取 Dlang 中的所有环境变量
- c# - 无法在 C#(本地计算机)中编辑 32 位注册表
- python - Pandas Rolling Groupby Shift back 1,试图滞后滚动总和