Presume we have the following code, where I defined a closure named closure
. Within this closure, I want to use the outer x
by immutable reference (&T
), and at the same time, using y
by taking ownership. How can I do that? If I use move
, all the outer variables that used in the closure will be moved into the closure. And also here the outer variable y
is copyable.
let x: i32 = 1;
let y: i32 = 2;
let closure = || {
println!("{}", x); // make sure x is used by &T.
// println!("{}", y); // how can I use y by taking its ownership?
};
closure();
Note that capturing by moving a reference is equal to capturing by reference.
When you add a move
keyword to the closure, yes, everything is captured by moving. But you can move a reference instead, which is what a closure without a move
keyword does.
let x: i32 = 1;
let y: i32 = 2;
let closure = {
let x = &x;
move || {
println!("{}", x); // borrowing (outer) x
println!("{}", y); // taking the ownership of y
}
};
closure();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With