Definition: Reference

reference is like a pointer in that it’s an address we can follow to access the data stored at that address; that data is owned by some other variable.

|500

Unlike a pointer, a reference is guaranteed to point to a valid value.

We call the action of creating a reference borrowing.

Definition: Mutable reference

If you have a mutable reference to a value, you can have no other references to that value, including immutable reference.

The benefit of having this restriction is that Rust can prevent data races at compile time

The scopes of the immutable references r1 and r2 end after the println! where they are last used, which is before the mutable reference r3 is created. These scopes don’t overlap, so this code is allowed: the compiler can tell that the reference is no longer being used at a point before the end of the scope.

let mut s = String::from("hello");
 
// let r1 = &s; // no problem
//          -- immutable borrow occurs here
// let r2 = &s; // no problem
// let r3 = &mut s; // BIG PROBLEM
//          ^^^^^^ mutable borrow occurs here
 
let r1 = &s; // no problem
let r2 = &s; // no problem
println!("{r1} and {r2}");
// Variables r1 and r2 will not be used after this point.
 
let r3 = &mut s; // no problem
println!("{r3}");

Definition: Dangling References

Dangling reference is a pointer that references a location in memory that may have been given to someone else—by freeing some memory while preserving a pointer to that memory.

In Rust, the compiler guarantees that references will never be dangling references: if you have a reference to some data, the compiler will ensure that the data will not go out of scope before the reference to the data does.

Dangling reference example:

fn main() {
    let reference_to_nothing = dangle();
}
 
fn dangle() -> &String {
    let s = String::from("hello");
    &s
//  ^^ Dangling
}

Because s is created inside dangle, when the code of dangle is finished, s will be deallocated. But we tried to return a reference to it. That means this reference would be pointing to an invalid String.

Rules of References

  • At any given time, you can have either one mutable reference or any number of immutable references.
  • References must always be valid.