Lending mutably

Sometimes, we want to lend a data value and allow the receiver to modify it, so that, after the borrow has ended, the data value in the owning scope has changed. When that's what we need, we lend the data mutably.

We can't lend mutably unless the data value we're lending is stored in a mutable variable, which means that the mut keyword was used when we declared the variable, like so:

let mut main_4 = main_2;

Given that we have a mutable variable to lend, we can create a mutable borrow of that variable's value, by using the mut keyword again, in a different context:

borrow_ownership_mutably(&mut main_4);

If there's a mutable borrow of a data value, creating another borrow for it (of either sort) is impossible and, if there are any immutable borrows, then creating a mutable borrow is impossible. That rule means that if a data value is mutably borrowed, it's not borrowed anywhere else. Combined with the rule we discussed earlier that prevents borrowed data from being changed by its real owner, that means that as long as there's a mutable borrow active, that borrow is the only way to modify the borrowed data value.

However, once the borrow is finished, the owner regains control of the (possibly modified) data value.

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

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