Ownership

Ownership prevents null ptrs and data races

  1. Each value in Rust has an owner.

  2. There can only be one owner at a time.

  3. When the owner goes out of scope, the value is dropped.

  4. Values can be moved between variables

Slices let you reference a contiguous sequence of elements in a collection rather than the whole collection

let x = 5;
let y = x;

println!("x = {x}, y = {y}"); //works fine, cuz on stack so fast

//different cuz on heap
let s1 = String::from("hello");
let s2 = s1;

println!("{s1}, world!"); //invalid bc since strings stored as ptr, rust auto declares s1 invalid

//instead
let s1 = String::from("hello");
let s2 = s1.clone();

println!("s1 = {s1}, s2 = {s2}");
  • calling functions auto pass ownership so no longer valid

References And Borrowing

  • references allow you to refer to some value without taking ownership of it

  • We call the action of creating a reference borrowing. As in real life, if a person owns something, you can borrow it from them. When you’re done, you have to give it back

  • Cant change

  • To change make mut

    • Mutable references have one big restriction: if you have a mutable reference to a value, you can have no other references(either mut or not) to that value.

  • note ref scope goes from init to last time its used so

  • rust will catch dangling ptrs

Last updated