Notes on Rust’s Borrowing Situations

This is my own notes from the original video by Gary Explains.

  • Immutable in Rust means read-only. (min. 10:10)
  • When using primitive types, you have to dereference them. (min. 11:51)
    The star-star thingy. *n = *n + 1

My personal notes for my self:

  • & can be taken as “borrow” the pointer.

Things to ask/revisit again:

fn main() {
    let a = 7;
    let mut b = a;
    b = b + 1;
    println!("a = {}, b = {}", a, b);
}
  • let mut b = a… How does the borrow go again?
    Is it because it is primitive type, so the borrow is kinda different? (i.e we can just copy-paste it because it is O(1)??)
    • I know that b is mutable, meaning that the b‘s value can be changed, so line 4 is giving new value there.
    • Update after learning bottom’s video: It’s because it was stored in stack, not heap. So when assigning stack thingy, Rust will copy the data there. Copying stack is MUCHH cheaper than copying object in heap.

Another thing

Personal comments: OMG this particular video so great! He mentions what makes it different from other languages, making it easier to notice “Oh, bener juga yak”. (Min. 9:56)

This one is because you always forget this!

  • Stack is in the processor’s L cache. (Code sample in ~3:40) Heap is in the… RAM I think.
  • Stack
    • Is fixed size, can’t grow. Usually things like primitive type, and fixed array (i.e let a:int[] = int[1,2,3,4]).
    • Can only live in the scope. Out of scope = delete!
  • Heap
    • Can grow in size.
    • May cost runtime performance (gotta go through memory bus lane).
    • Can live outside of the scope.
      Will be cleaned when the LAST owner goes out of scope.

The long notes:

  • Box<T> Will push your usize types to heap! So you can pass it to someone else along the way! → Wrong.
    TODO: My homework to learn when to use Box<T>, Rc<T> and RefCell<T>.
  • Stack copies are very cheap, Rust will default to this, whenever it can.
  • & → Borrow the ownership as a reference!
  • When dev see the & in param in function call, it tells dev that the variable is being borrowed for the procedure call, and the owner will be returned after the procedure call is done.
  • str is called “String Slice“.
    More info: https://doc.rust-lang.org/book/ch04-03-slices.html
  • “Unless you need to pass a mutable string to a function or procedure, it’s recommend you make your parameter to be a string slices.” (Min. 23:07)
  • Copy derive macro may not be performant, so Rust will default not to Copy!
    If you’re sure the struct is small enough to be performant (small members), you can choose so!
    TODO: I need to check this again! Welp, another homework.
  • Copy macro requires Clone macro too! (Min. 32:41)

Disclaimer:

Not all articles here are meant to be correct. My notes might be wrong or may no longer be relevant. If you want to try things here, please proceed with caution.


Posted

in

by

Tags: