Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I capture some things by reference and others by value in a closure?

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();
like image 888
Jason Yu Avatar asked Dec 23 '22 15:12

Jason Yu


1 Answers

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();
like image 131
Alsein Avatar answered Dec 26 '22 02:12

Alsein