Logo Picture

Visualizing Ownership and Borrowing in Rust Programs

About you

Beginner: fundamental knowledge

Student: actively learning

Professional: working in the industry for >1 year

Expert: working in the industry for >5 years

Rust


is a modern programming language recognized for prioritizing safety, reliability, and performance. It features a unique ownership system for memory management that prevents common programming errors, making it well-suited for building robust and efficient software.


Here is a short overview over Rust's memory management model utilizing interactive visualizations.


Ownership


In Rust you can bind a value to an owner using the statement:


let owner = value;


Rules:

  • Each value in Rust has an owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value will be dropped (and its memory freed).


Click on variables to visualize an ownership/ borrowing graph.

  • the first line assigns ownership over the string "Hello world" to x
  • in the second line the ownership over the string is moved to mine_now
  • accessing x after that would be a compile error


Primitive Types


One exception to these ownership rules are primitive values (e.g., numbers).

When a primitive value is used, its value is implicitly copied, instead of moving its ownership.

Note how n is used in multiple places, without transferring ownership of its value.

Mutability


By default, all variables in Rust are readonly.

To mutate/write to an existing value, it's owner must be marked mutable (mut) explicitly.


Thicker lines indicate mutable values.

Note that the last line, would cause a compile error, as doubled is not mutable.

Borrowing


Instead of passing ownership to a value, we can also borrow the value from its owner with the &-operator.

When the owner is marked as mutable, we can also create a mutable reference (&mut) to the value (which allows writing to it).


Rules:

  • At any given time, you can have either one mutable reference or any number of immutable references to a value.
  • References must always be valid, so the value must not be moved while it is referred to.


These are the basic principles of Rust's memory management (more information can be found here).


Please rate the following statements about the visualizations

1: complete disagree

2: slight disagree

3: neutral

4: agree

5: fully agree

Would you detect errors faster compared to console-based borrow checker errors?

1
2
3
4
5

or deepened your (intuitive) understanding if you were already familiar with these concepts.

1
2
3
4
5

Making Rust easier and faster to learn for new programmers, and ones switching from other languages.

1
2
3
4
5

Assuming they were directly integrated into your IDE.

1
2
3
4
5

Powered by OpnForm