TExcelTAD
Home › Rust › Rust Ownership

Rust Ownership

Ownership is the feature that makes Rust different from almost every other language. It is how Rust manages memory without a garbage collector and without manual free calls — and it is checked entirely at compile time, so it costs nothing while your program runs.

The three rules

  1. Every value in Rust has a single owner (a variable).
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value is dropped (its memory is freed).

That's it. Everything else in this chapter follows from these rules.

Stack and heap, briefly

Simple values with a fixed size — integers, floats, bool, char — live on the stack and are cheap to copy. Values that can grow, such as String and Vec, keep their contents on the heap; the variable itself holds a small pointer, length and capacity. Ownership is mostly about who is responsible for freeing that heap memory.

Moving a value

When you assign a String to another variable, Rust does not copy the heap text. It moves ownership: the new variable becomes the owner and the old one can no longer be used.

rust · try it yourself
fn main() {
    let a = String::from("lunchbox");
    let b = a; // ownership moves from a to b

    println!("b owns: {}", b);
    // a can no longer be used here
}
b owns: lunchbox

If you try to use a after the move, the program will not compile:

rust
fn main() {
    let a = String::from("lunchbox");
    let b = a;
    println!("{}", a);
}
text
error[E0382]: borrow of moved value: `a`
 --> src/main.rs:4:20
  |
2 |     let a = String::from("lunchbox");
  |         - move occurs because `a` has type `String`, which does not implement the `Copy` trait
3 |     let b = a;
  |             - value moved here
4 |     println!("{}", a);
  |                    ^ value borrowed here after move

Why so strict? If both a and b owned the same heap text, both would try to free it at the end of main — a "double free" bug. By allowing only one owner, Rust makes that impossible.

Copy types

Small stack-only types implement the Copy trait. Assigning them makes a cheap bit-for-bit copy, and both variables stay valid.

rust · try it yourself
fn main() {
    let x = 10;
    let y = x; // i32 is Copy: x is copied, not moved

    let flag = true;
    let other = flag;

    println!("x = {}, y = {}", x, y);
    println!("flag = {}, other = {}", flag, other);
}
x = 10, y = 10
flag = true, other = true
Copied on assignment (Copy) Moved on assignment
i32, u8, f64 and all other numbers String
bool, char Vec<T>
tuples/arrays made only of Copy types Box<T>, HashMap and most structs

Cloning: an explicit deep copy

If you really want two independent copies of heap data, ask for one with .clone(). Cloning is visible in the code on purpose, because it can be expensive.

rust · try it yourself
fn main() {
    let original = String::from("recipe");
    let mut copy = original.clone();
    copy.push_str(" (edited)");

    println!("original: {}", original);
    println!("copy    : {}", copy);
}
original: recipe
copy    : recipe (edited)

Ownership and functions

Passing a value to a function works exactly like assignment: a String is moved into the function's parameter, and dropped when the function ends — unless the function gives it back by returning it.

rust · try it yourself
fn take(text: String) {
    println!("take() now owns: {}", text);
} // text is dropped here

fn take_and_give_back(mut text: String) -> String {
    text.push('!');
    text // ownership moves back to the caller
}

fn make_copy(n: i32) {
    println!("make_copy() got: {}", n);
}

fn main() {
    let s1 = String::from("hello");
    take(s1);
    // s1 is gone now

    let s2 = String::from("hey");
    let s3 = take_and_give_back(s2);
    println!("Got back: {}", s3);

    let n = 5;
    make_copy(n);
    println!("n is still usable: {}", n);
}
take() now owns: hello
Got back: hey!
make_copy() got: 5
n is still usable: 5

Moving values in and out of every function would get tiresome quickly. Luckily there is a better way: borrowing, which lets a function use a value without taking ownership. That is the topic of the next chapter.

Tip: When the compiler says "value used here after move", ask yourself: should the function borrow the value (&T) instead of taking it, or do I really need a .clone()?

Go further: Rust: Ownership, unsafe, FFI and Migration maps the borrow checker's rules to the C bug classes it rules out.

Test yourself

After let a = String::from("x"); let b = a;, which variable can be used?

  1. Both a and b
  2. Only a
  3. Only b
  4. Neither

Why can you still use x after let x = 5; let y = x;?

  1. Integers implement Copy, so x is copied
  2. Integers are always borrowed
  3. Rust ignores ownership for let
  4. y is a reference to x

When is the memory of a String freed?

  1. When the garbage collector runs
  2. When you call free()
  3. When its owner goes out of scope
  4. Never