Dev Notes

Software Development Resources by David Egan.

The Rust Ownership Model


Rust
David Egan

Rust manages heap memory through a system of ownership, whereby the compiler checks a set of rules at compile time.

Ownership features do not slow down the compiled code - if the code has compiled, it has satisfied all necessary ownership requirements.

Ownership Rules

  • Each value has a variable called it’s owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value is dropped.

If a value is heap allocated (i.e. it’s size is not known at compile time), copies are shallow by default and the original is invalidated. This is like a C++ move.

When a variable that includes heap-allocated data goes out of scope, the value is cleaned up by drop unless the data has been moved - i.e. another variable has taken ownership.

Rules of Borrowing

  1. Unlimited borrows for read-only borrows: let a = &x
  2. For a read only borrow, the original data is immutable for the duration of the borrow
  3. You can only have a single borrow at a time for mutable borrows: let a = &mut x

Example Borrow

fn main() -> Result<(), &'static str> {
    let mut a = [1,2,3,4];
    println!("{:?}", a); // Line 1 output
    
    {
        let b = &mut a[0..2];
        // You can't access a at this point because it has been mutably borrowed
        // from. The following line won't compile, with the error message:
        // `cannot borrow `a` as immutable because it is also borrowed as mutable`:
        // println!("a: {:?}", a);

        println!("b: {:?}", b); // Line 2 output
        b[0] = 42;
        println!("b: {:?}", b); // lIne 3 output
    }

    // The borrow is scope-dependent - a is accessible again because the 
    // variable that borrowed it is out of scope:
    println!("a: {:?}", a); // Line 4 output
    Ok(())
}

Output:

[1, 2, 3, 4]
b: [1, 2]
b: [42, 2]
a: [42, 2, 3, 4]

Rust References

Two kinds:

  • Shared reference: &
  • Mutable reference: &mut

A reference cannot outlive it’s referent.

A mutable reference cannot be aliased.

Note that aliased is not yet defined.

The Rules of Referencing

  • At any given time, you can have either one mutable reference or any number of immutable references.
  • References must always be valid - dangling pointers won’t compile - the thing being referred to must be in scope.

Aliasing

Variables and pointers alias if they refer to overlapping regions of memory.

References


comments powered by Disqus