The Rust borrowing rules

There are two rules that must be observed with borrowing, which are as follows:

  • What you borrow must not outlive the original
  • You can have one of the following types of borrow, but never at the same time:
    • One (or more) references of type &T to a resource
    • Only one mutable reference

The first rule makes sense: you can't have the reference outlive where it came from as once where it comes from goes out of scope, it is destroyed and, once destroyed, what are you borrowing exactly?

The second one requires a bit more thought about why it is as it should be and what it is that Rust is trying to achieve.

In this case, Rust is ensuring that something known as a race condition occurs (if you are used to writing multithreaded applications, you'll already understand these).

Here, Rust is trying to prevent two references trying to access the same point of memory at the same time. In other words, Rust is trying to prevent a synchronization error.

With non-mutable references, you can have as many as you'd like, as the references can never be written to. With a mutable reference, Rust prevents the problem by allowing just a single reference to be valid.

With this in mind, can we use these rules to fix our code from mutableref2 in order to do away with the {} braces around the mutable reference?

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

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