Why does Rust Closure take ownership before being called

Viewed 357

I'm going through the Rust book, and I'm on the chapter describing closures. 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? 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?

1 Answers

Because a closure is essentially a struct with a function associated with it. 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.

Related