Rust Lifetimes

2019-09-05

Roland Brand

Sources

Paradigms

  • Memory Safety
  • Copy and Move: Two types of assignment
  • A Tree of Values instead of a See of Objects

Memory Safety (if you're coming from C/C++)

Memory Safety if you're coming from Java/JS/PHP/Python...

  • We're already used to memory safety (as long as we're talking single threaded)
  • These languages almost completely hide memory management away from the developer
    • easy to use
    • high runtime overhead
    • hard to optimize
  • We're at the slow end of the
    "Garbage Collector Gap"

Copy vs. move

  • copy for primitive values is familiar
  • for references to the heap we are usually more familiar with clone instead of move

lifetimes make sure we cannot have references to moved values at any time

A sea of objects

 

  • Rust aims to avoid the "sea of objects" which typically arises with (undisciplined) OOP

Step by Step Concepts

  • Stack vs Heap
  • Ownership
  • Drop
  • Borrowing Checker

Stack vs. Heap

Ownership

Title Text

Drop

  • at the end of scope ( } ) all values owned by the scope are dropped if they haven't been moved yet
  • return moves the value to the parent stack frame
  • no garbage collection! Memory is freed immediately

Borrow checker

  • Within the same lifetime:
    • You can borrow either
      • one mutable reference
      • many immutable references

Lifetimes and scope

Lifetime specifiers

Rust

JS etc.

C/C++

?

primitive assignment

assignment by reference (object)

...this is what we are used to (behind the scenes)

a = b

doSomething(b)

Copy trait

Move trait (b becomes unusable)

borrowing

Rc

Cell / RefCell

If you're struggling with lifetimes, maybe you don't have to

  • If you need behavior from familiar OOP patterns, you can use Rc and RefCell.
  • However, this is very verbose and you might be using Rust wrong
  • How about
    • (idempotent) functional programming with little state, reactive patterns, pattern matching with match and algebraic enum types
    • Use crates for complex data structures
    • Use other languages for the high level smalltalk, and Rust for powerful libraries

RefCell example

Rust Lifetimes

By Roland Brand

Rust Lifetimes

  • 79