4

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();
trent
  • 21,712
  • 7
  • 47
  • 79
Jason Yu
  • 1,646
  • 12
  • 17
  • 1
    jut add a `let x = &x;` line before your closure ? – Denys Séguret Apr 23 '21 at 13:07
  • Here are some other questions with answers that mention the same idea: [Why is the value moved into the closure here rather than borrowed?](https://stackoverflow.com/q/38913472/3650362) and [Mutably borrow one struct field while borrowing another in a closure](/q/36379242/3650362) – trent Apr 23 '21 at 13:24

1 Answers1

11

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();
user4815162342
  • 124,516
  • 15
  • 228
  • 298
Alsein
  • 3,459
  • 13
  • 30
  • 4
    Another useful idiom is to open a scope to create the closure, and use `let x = &x` to force borrowing in an otherwise `move` closure: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9e241b2b4394dcdcb715c9ef4bdba919 – user4815162342 Apr 23 '21 at 13:45
  • @user4815162342 Nice practice! I have updated my answer. – Alsein Apr 25 '21 at 07:31
  • 1
    Thanks; I've gone ahead and updated the comment accordingly. – user4815162342 Apr 25 '21 at 08:03