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.

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);

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

If the compiler cannot determine the output lifetime parameters, you need to annotate it for the compiler.