Rust
Table of Contents
These are notes of watching this playlist.
Defaults
- immutable;
- move
- when the resource is on heap, implicit
unique_ptr
. (think in a C++ way) - when it is on stack, see Move and Copy.
- when the resource is on heap, implicit
Borrow (Reference)
- One mutable ref, or any number of immutable ref.
- Compiler checks whether a ref is still valid (the original copy does not go out of scope).
- when a mutable variable is borrowed (even imutable borrow), you cannot mutate the original variable during borrowing.
- no need to wait for the ref to go out of {}, as long as it is no longer used, its lifetime ends.
Ownership
rust's ownership mode is just like c++ RAII (or unique_ptr
if on heap). That is also why it is moved by default.
- one and only one owner
- when the owner goes out of scope, the resource is deallocated.
Move and Copy
let b = a; func(a);
- For variables on the heap, or struct with variables on the heap, they are moved.
- For variables on the stack that have copy trait implemented (e.g. primitives like i32), they are copied.
- For variables on the stack that don't have copy trait implemented, they are "moved". In fact, they are copied, but the original stack memory is marked as moved by the compliler.
- Rust won’t let us annotate a type with Copy if the type, or any of its parts, has implemented the Drop trait. This means for variables on the heap, or struct with variables on the heap, they cannot implement copy trait, thus always be moved.
lifetime
A function/method may return a reference.
The compiler determines the lifetime of the returned reference based on these rules.
- Each parameter that is a ref gets its own lifetime parameter
- If there is exactly one input lifetime parameter, that is assigned to all output lifetime parameters
- If there are multiple input lifetime parameters, but one of them is &self, or &mut self. The lifetime of self is assigned to all output parameters