Mutable borrows

This is more a writable DVD than a prerecorded one if we use the analogy of borrowing a DVD.

Here, we are using a mutable reference, and we have to be careful how we use these.

The code for this section is in the 08/mutableref1 and 08/mutableref2 folders in the supporting code bundle provided for this book.

In our first example (mutableref1), we will create a variable, the reference, do something, and get a new value out:

fn main()  
{ 
    let mut mutvar = 5; 
    { 
        println!("{}", mutvar); // outputs 5 
        let y = &mut mutvar; // creates the mutable ref to mutvar 
        *y += 1; // adds one to the reference and passes it back in to mutvar 
    } 
    println!("{}", mutvar); // outputs 6 
} 

The important line here is *y += 1; and, in particular, the *, as this means we're directly altering the value of the memory position that the reference points to. When dealing with anything to do with memory, absolute care has to be observed.

The second important point to observe is that we have a set of braces around the code used in the mutable reference. Remove them and everything fails (mutableref2):

The important line is the result of the error; it is saying that you cannot borrow the same item as both mutable and immutable at the same time. It's like saying you can borrow something that can and can't be changed at the same time! Utter nonsense. This is down to borrowing having rules.

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

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