Hacker News new | ask | show | jobs
by zphds 3430 days ago
Here's my understanding. Please correct me if I am wrong. Visualizing your program as a tree of values that are borrowed, owned, mutated through variables helps in reasoning about the borrow checker

When a variable owning a value goes out of scope all the children goes with it. Remember in rust, there can only be one owner to a value (Rc and Arc variables lets you have multiple owners but that's for special cases). Therefore, if you're passing a variable to a function you should either

1.) transfer ownership to the function being called.

2.) have the function being called borrow the value through references. Since this doesn't transfer any ownership you can have multiple references to the same value. The value and its children (think of a Vec<Animal>) are taken down from the tree it belongs when the variable owning this value goes out of scope.

That's the cool thing that does rust does. The compiler knows when to free things just by following this one rule. A value should have only one owner. The responsibility of managing memory is now taken by the compiler instead. Hence no dangling pointers or segmentation fault unless you use `unsafe` blocks where this assurance isn't valid anymore.

Visualize your program to be manipulating these multiple trees made up of diverse types.