Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active July 10, 2021 13:35
Show Gist options
  • Save rpivo/4239b2213ea27d2d2f8b7552ff259482 to your computer and use it in GitHub Desktop.
Save rpivo/4239b2213ea27d2d2f8b7552ff259482 to your computer and use it in GitHub Desktop.
Ownership & Borrowing in Rust

Ownership & Borrowing in Rust

Rust doesn't have traditional garbage collection, but instead has other mechanisms to free up memory as quickly and safely as possible.

One mechanism Rust uses to free up memory is called ownership. This happens when a complex type such as a Vec is used in a different scope than it was declared, which results in the new scope taking "ownership" of the variable.

For simpler types, ownership does not come into play. The below code is completely valid.

fn main() {
    let n = 1;
    
    some_cool_func(n);
    
    println!("{}", n);
}

fn some_cool_func(val: i32) {
    println!("{}", val);
}

However, taking a look at the same example where variable n is a vector, we can see ownership taking place.

fn main() {
    let n = vec![1,2,3];
    
    some_cool_func(n); // n changes ownership
    
    for x in n { println!("{}", x); } // ERROR - ownership of n has moved!
}

fn some_cool_func(val: Vec<i32>) {
    for n in val { println!("{}", n); }
}

This error is actually good -- it forces the user to consider writing code that's more careful with memory usage. However, if the variable is needed in multiple scopes, Rust allows us to borrow by reference.

To do this, we need to pass in a reference (prefixed with an ampersand &) to some_cool_func(). We also need to adjust the argument type for some_cool_func() to expect a reference to a vector containing 32-bit integers: &Vec<i32> instead of Vec<i32>.

fn main() {
    let n = vec![1,2,3];
    
    some_cool_func(&n); // n ownership stays the same, just passing a reference
    
    for x in n { println!("{}", x); } // OKAY!
}

fn some_cool_func(val: &Vec<i32>) {
    for n in val { println!("{}", n); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment