简体   繁体   English

为什么 Rust 闭包在被调用之前取得所有权

[英]Why does Rust Closure take ownership before being called

I'm going through the Rust book, and I'm on the chapter describing closures.我正在阅读 Rust 书,并且正在描述闭包的章节。 I'm a bit confused about why the following example errors due to the closure taking ownership:我对为什么由于闭包获得所有权而出现以下示例错误感到有些困惑:

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));
}

Namely, why does equal_to_x take ownership of x before it's even called?也就是说,为什么equal_to_x甚至在它被调用之前就获得了x的所有权? Shouldn't the compiler know that the closure hasn't been called (because it is owned by main ) and thus x can still be owned by the outside scope of main ?编译器不应该知道没有调用闭包(因为它归main拥有),因此 x 仍然可以归main的外部 scope 拥有吗?

Because a closure is essentially a struct with a function associated with it.因为闭包本质上是一个结构,它带有一个与之关联的 function。 I find it easier to think of closures like this:我发现更容易想到这样的闭包:

struct MyClosure{
    x: Vec<i32>
};

impl MyClosure {
    pub fn execute(self, z: Vec<i32>) -> bool {
        z == self.x
    }
}

If thought of like this, your code is equivalent to如果这样想,你的代码相当于

let equal_to_x  = MyClosure {
    x
};

so you can see why the move has happened.所以你可以看到为什么会发生这个动作。

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

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