Jason Yu
Jason Yu

Reputation: 2038

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

Upvotes: 6

Views: 5855

Answers (1)

Alsein
Alsein

Reputation: 4765

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

Upvotes: 22

Related Questions