Using references in Rust is called Borrowing.
Here is a simple example:
There are two borrowing rules:
1. at any given time, you can have either one mutable reference or any number of immutable references
example:
borrowing is not violated here because these references (and original value) is immutable (no values were manipulated only read; not updated/written)
but if we do this instead (add themut
keyword for s1
)
if you get the next reference then you are understanding why this is important:
Why would this not work?
Answer
- because
.last()
takes ownership of the value of x due to the function pass of.last().unwrap()
- so if the compiler did not catch our error
- last could be pointing to a memory location that does not exist anywhere.
Correct Code:
This way there is only one mutable reference to x.
2. References must always be valid.
since the r
owner definition was dropped when leaving the inner scope.
the println!
statement would not work due to no borrow / references existing on the heap / memory.
The does not live long enough
is a Rust attribute called Lifetimes