Borrowing rules

Similar to the ownership rule, we also have borrowing rules that maintain the single ownership semantics with references, too. These rules are as follows:

  • A reference may not live longer than what it referred to. This is obvious, since if it did, it would be referring to a garbage value.
  • If there's a mutable reference to a value, no other references, either mutable or immutable references, are allowed to the same value in that scope. A mutable reference is an exclusive borrow.
  • If there is no mutable reference to a thing, any number of immutable references to the same value are allowed in the scope.
The borrowing rules in Rust are analyzed by a component of the compiler called the borrow checker. The Rust community amusingly calls dealing with borrowing errors as fighting the borrow checker.

Now that we're familiar with the rules, let's see what happens if we go against the borrow checker by violating them.

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

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