Lending

There's one more way we can send information to a different scope and that is by lending. When we move a data value, the receiving scope becomes the value's new owner. When we copy a data value, the receiving scope owns the duplicate it received, and the sending scope retains ownership of the original. When we lend a data value, things can get more complicated, because the original scope retains ownership, but the receiving scope is still allowed to access the data.

The original scope still owns the data, which means that, when that scope ends, the data will go away. If some of the scope's contained data was still loaned to a different scope at that time, the program would likely crash and, since the Rust compiler hates potential crashes, it does not allow us to get into that situation. Instead, it requires that any borrowed information must be returned before the owning scope's time is up.

When a data value is borrowed, that value is neither copied nor moved. The bytes that represent that value on the stack stay right where they were. Instead, the borrower receives the memory address of those bytes on the stack, allowing it to violate the conceptual idea of a stack by accessing information stored below the top, probably in a different scope entirely. You can see why the compiler wants to be careful about that!

A currently borrowed data value can't be changed by the owner, even if the data value is stored in a mutable variable. This is part of keeping lending from causing problems: a data value can only ever be changed in one place at a time at most and, when it can be changed, it's never in use elsewhere.

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

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