rust - 为什么移动闭包不拥有变量的所有权?

标签 rust closures

<分区>

The Rust Programming Language says :

If you want to force the closure to take ownership of the values it uses in the environment, you can use the move keyword before the parameter list

我注意到我的代码不会拥有这些值的所有权。我的代码与给定示例之间的区别是:

  • 使用整数代替 Vec
  • 使 x 可变而不是不可变

示例 1:Rust 编程语言

fn main() {
    let x = vec![1, 2, 3];

    let equal_to_x = move |z| z == x;

    println!("can't use x here: {:?}", x);

    let y = vec![1, 2, 3];

    assert!(equal_to_x(y));
}

示例 2:我的代码

fn main() {
    let mut x = 1;

    let equal_to_x = move |z| z == x;

    println!("can use x here: {:?}", x);

    let y = 1;

    assert!(equal_to_x(y));
}
  1. 为什么示例 2 会编译而示例 1 不会?

  2. A即使我在闭包前面显式地写了move,为什么x 的所有权没有被移动?为什么 x 移入闭包后可以访问?

最佳答案

答案在你第一个例子的错误信息中给出

error[E0382]: borrow of moved value: `x`
 --> src/main.rs:6:40
  |
2 |     let x = vec![1, 2, 3];
  |         - move occurs because `x` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
3 | 
4 |     let equal_to_x = move |z| z == x;
  |                      --------      - variable moved due to use in closure
  |                      |
  |                      value moved into closure here
5 | 
6 |     println!("can't use x here: {:?}", x);
  |                                        ^ value borrowed here after move

“发生移动是因为 x 具有类型 std::vec::Vec<i32>,它没有实现 Copy 特征”

这意味着,当一个类型实现了 Copy trait(就像 i32 所做的那样),move 将变量复制到闭包的范围内。

关于rust - 为什么移动闭包不拥有变量的所有权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56076786/

相关文章:

r - 错误 : configuration failed for package ‘gifski’

rust - 如何为 Iterator::filter_map 指定类型信息?

Rust 自定义可索引数据类型

swift - 使用 Swift 闭包和 Firebase 处理异步数据

functional-programming - 关闭因为它可以做什么或因为它做了

javascript - 需要解释 : Cannot understand javascript returning a function

javascript - 为什么 javascript 的 Closure 属性不适用于父对象

rust - 如何将 -L 链接器标志传递给基于 cargo 的项目的 rustc?

module - 如何跨模块文件使用宏?

javascript - 这两个javascript函数有什么区别?