Ownership and Borrowing

index > dev > language > rust

Video Tutorial: https://www.youtube.com/watch?v=lQ7XF-6HYGc

And here are some notes from the video:

Stack v.s. Heap

Stack

Heap

Ownership

Solution

fn main() {
    let heap_f64: Box<f64> = Box::new(2.);
    heap_procedure(heap_f64);
    println!("In main heap {}", heap_f64);
}

fn heap_procedure(param: Box<f64>) {
    param += 9.
    println!("In heap procedure {}", param);
}

For a Heap variable, passing it as a parameter of function means transfer its ownership to the new parameter variable. And when the inner function is over, it is cleaned up automatically. Thus, it failed compiling.

Now, let do the borrowing:

fn main() {
    let heap_f64: Box<f64> = Box::new(2.);
    heap_procedure(&heap_f64);
    // or just simply clone:
    //   heap_procedure(heap_f64.clone());
    println!("In main heap {}", heap_f64);
}

fn heap_procedure(param: &Box<f64>) {
    param += 9.
    println!("In heap procedure {}", param);
}

Why this is necessary?


Thanks Doug Milford for this awesome video!