0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Understanding Rust `move` keyword

Posted at

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 yand 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!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?