简体   繁体   English

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

[英]Why doesn't a move closure take ownership of a variable?

The Rust Programming Language says : Rust编程语言

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 如果要强制闭包对其在环境中使用的值拥有所有权,则可以在参数列表之前使用move关键字

What I have noticed with my code is that it won't take ownership of these values. 我在代码中注意到的是,它不会拥有这些值的所有权。 The differences between my code and the given example are: 我的代码和给定示例之间的区别是:

  • using an integer instead of a Vec 使用整数而不是Vec
  • making x mutable instead of immutable 使x可变而不是不变

Example 1: The Rust Programming Language 示例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));
}

Example 2: My Code 示例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. Why will example 2 compile but example 1 won't? 为什么示例2会编译而示例1不会编译?

  2. AWhy is the ownership of x not moved even if I explicitly write move in front of the closure? A为什么即使我在闭包前面显式写入movex的所有权也不会移动? Why is x accessible after moving it into the closure? x移入闭包后为什么可以访问x

The answer is given in the error message of your first example 在第一个示例的错误消息中给出了答案

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

"move occurs because x has type std::vec::Vec<i32> , which does not implement the Copy trait" “发生移动是因为x类型为std::vec::Vec<i32> ,它没有实现Copy trait”

This means, when a type implements the Copy trait (like an i32 does), move copies the variable into the scope of the closure. 这意味着,当一个类型实现Copy特性(如i32一样)时,将变量复制到闭包的范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM