What is the move parameter?

The move parameter forces the closure to take ownership of whatever is contained within. Let's look at that a bit closer:

let myNum = 10; 
let myMove = move |x: i32| x + myNum; 

Here, myMove takes ownership of myNum. The value of myNum implements Copy, which is assigned to the binding. This is the same as the operation of any variable, so there has to be something to differentiate move from anything else.

Let's look at a slightly different example and see if we can see what is actually going on:

let mut myMutNum = 10; 
{ 
    let mut subNum = |x: i32| num -= x; 
    subNum(3);  
} 

We've seen this before, so it should not be too hard to understand. This would give the answer 7. If we used move, however, the answer may not be as expected:

fn main()  
{ 
    let mut my_mut_num = 10; 
    { 
        let mut sub_num = move |x: i32| my_mut_num -= x; 
        sub_num(3);  
    } 
    println!("{}", my_mut_num); 
} 
The code for this example is in Chapter 11/move_closure_one.

When compiled, you may expect the answer 7, but instead you get:

Figure 12

How can we have a value of 10?

In the nonmove version, we borrow the value of the mutable. With move, we take ownership of a copy. In practical terms, we have created a completely new stack frame for the closure. The sub_num() call is still being executed, but when it is called, the value returned is not the expected one, but the ownership of the copy of the original value (10).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset