Rust's move
keyword always bothers me so, I decided to write my understanding which I obtained after thorough discussion with my colleague @YushiOMOTE.
I hope this might help someone.
let x = 1;
In the above statement, x is a variable whose value is 1. Now,
let y = || println!("y is a variable whose value is a closure");
So, move
keyword is used to transfer the ownership of a variable to the closure.
In the below example, without move
, x
is not owned by the closure. Hence x
is not owned by y
and available for further use.
let x = 1;
let y = || println!("this is a closure that prints x = {}". x);
On the other hand, in this next below case, the x
is owned by the closure. x
is owned by y
and not available for further use.
let x = 1;
let y = move || println!("this is a closure that prints x = {}". x);
By owning
I mean containing as a member variable
. The example cases above are in the same situation as the following two cases. We can also assume the below explanation as to how the Rust compiler expands the above cases.
The formar (without move
; i.e. no transfer of ownership),
struct ClosureObject {
x: &u32
}
let x = 1;
let y = ClosureObject {
x: &x
};
The later (with move
; i.e. transfer of ownership),
struct ClosureObject {
x: u32
}
let x = 1;
let y = ClosureObject {
x: x
};
Please share your views on my understanding!!