Blog

Part 6 · Ownership and Moves in Rust: Who Owns This Value?

Every value in Rust has exactly one owner. Assigning a String to another variable moves it, and the old name stops working. This part shows what a move does in memory, why Rust needs it, and how Copy, clone and drop fit in.

Every value in Rust has one owner. When the owner goes away, Rust frees the value. That single rule replaces a garbage collector, and it’s the reason Rust code can’t free the same memory twice.

This part covers what a move does, what lives on the stack and what lives on the heap, Copy and clone, moves into and out of functions, and when Rust runs drop. Every program here was run on Rust 1.95, and its output is pasted from the run. To run one yourself, put it in src/main.rs of a cargo new project and type cargo run.

Try this first

Read this program and decide what it prints before you scroll down:

fn main() {
    let a = String::from("hello");
    let b = a;
    println!("{a}");
    println!("{b}");
}

It doesn’t print anything. It doesn’t compile:

error[E0382]: borrow of moved value: `a`
 --> src/main.rs:4:16
  |
2 |     let a = String::from("hello");
  |         - 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

In most languages, let b = a gives you two names for the same text, and both work. In Rust, let b = a moves the string from a to b. After that line, a no longer owns anything, and the compiler won’t let you use it.

Read the error from the bottom up. Line 4 uses a. Line 3 is where a lost its value. Line 2 says why it was moved instead of copied: a String doesn’t implement Copy. We’ll get to Copy below. Notice the error code, E0382. You’ll see it often, and rustc --explain E0382 prints a full page about it.

The three rules

Rust’s ownership comes down to three rules:

  1. Every value has one owner, a variable or something else that holds it.
  2. There is only one owner at a time.
  3. When the owner goes out of scope, the value is dropped, and its memory is freed.

Rule 2 is why a stopped working. If both a and b owned the string, rule 3 would free it twice: once when b goes out of scope and once when a does. Freeing the same memory twice is a real bug in C and C++, called a double free. It can crash a program or corrupt memory. Rust rules it out before the program runs.

What a String looks like in memory

To see what a move does, we need to see what a String is. It has two parts:

  • a small, fixed-size part: a pointer to the text, the length, and the capacity;
  • the text itself, in a buffer on the heap.
fn main() {
    let a = String::from("hello");
    println!("text:     {a}");
    println!("length:   {}", a.len());
    println!("capacity: {}", a.capacity());
    let size = std::mem::size_of::<String>();
    println!("String itself takes {size} bytes");
}

It prints:

text:     hello
length:   5
capacity: 5
String itself takes 24 bytes

The 24 bytes are the three numbers, 8 bytes each on a 64-bit machine. They live wherever the variable lives, which for a is the stack. The 5 bytes of “hello” live on the heap. A longer string makes the heap buffer bigger, but the String itself stays 24 bytes. Rust doesn’t promise the order of the three numbers inside a String, so the figures below just pick one.

The length is how many bytes are in use. The capacity is how many the buffer can hold before it needs a bigger one. We’ll need the capacity in Part 8, when a Vec outgrows its buffer.

Watching a move

The animation steps through let a = String::from("hello"); let b = a; and then the end of main. The stack is on the left and the heap is on the right. In this series, a solid arrow always means “owns”.

stack heap a len 5 cap 5 ptr moved h e l l o freed b len 5 cap 5 ptr owner of the bytes: a a and b hold the same pointer owner of the bytes: b (a is moved) b dropped: the bytes are freed once let a = String::from("hello"): a owns 5 bytes on the heap let b = a: the 3 stack numbers are copied, the heap bytes are not a is now moved: the compiler won't let you use it end of main: b is dropped and frees the bytes; a owns nothing

A move copies the three numbers on the stack and nothing on the heap. Then the old name is marked as moved, so only one owner is left to free the bytes.

Here are those steps in words, in case the animation doesn’t play for you:

  1. let a = String::from("hello") puts a length of 5, a capacity of 5 and a pointer into a, on the stack. The pointer leads to the five bytes of “hello” on the heap. a owns those bytes.
  2. let b = a copies the three numbers from a into b. The heap bytes aren’t copied. For a moment, both pointers lead to the same buffer.
  3. The compiler now treats a as moved. Its value is still sitting on the stack, but you can’t use it, so b is the only owner.
  4. At the end of main, b goes out of scope. Rust drops it, and that frees the heap bytes. a isn’t dropped, because it owns nothing. The bytes are freed exactly once.

We can check step 2 on a real program. as_ptr returns the address of the heap buffer:

fn main() {
    let a = String::from("hello");
    let before = a.as_ptr();
    let b = a;
    println!("b still uses the same heap bytes: {}", b.as_ptr() == before);

    let c = b.clone();
    println!("c uses the same heap bytes: {}", c.as_ptr() == b.as_ptr());
    println!("b = {b}, c = {c}");
}

It prints:

b still uses the same heap bytes: true
c uses the same heap bytes: false
b = hello, c = hello

After the move, b points at exactly the buffer a pointed at. Nothing on the heap moved. The second half uses clone, which we’ll cover next. It makes a new buffer, so c points somewhere else.

Explain it like I’m ten

Picture a library book with a card in the front. The card has one name on it: the person who has the book right now. When you hand the book to your friend, the librarian crosses your name out and writes theirs. You can’t take the book home any more. Your name is crossed out, even if you still remember which shelf it came from.

When your friend is done, they return the book. It goes back once, because only one name is on the card. Nobody can return it a second time.

The precise version

A move copies the bytes of the value from the old place to the new one. For a String, those are the 24 bytes of pointer, length and capacity. Then the compiler marks the old variable as moved. Reading it is a compile error, and Rust won’t drop it at the end of its scope. All of this is decided when the program compiles. At run time, a move is a plain copy of a few bytes. There’s no counter and no check.

Where the analogy breaks: the librarian works while the program runs. Rust’s “librarian” is the compiler, and it finishes before the program starts. Also, a book is one thing that changes hands. A String is two things: the small part on the stack, which really is copied, and the buffer on the heap, which stays where it is.

Copy types don’t move

Integers behave the way you’d expect from other languages:

fn main() {
    let x = 5;
    let y = x;
    println!("x = {x}, y = {y}");

    let point = (1.5, 2.5);
    let copy = point;
    println!("{point:?} {copy:?}");
}

It prints:

x = 5, y = 5
(1.5, 2.5) (1.5, 2.5)

An i32 has no heap part. Copying its 4 bytes gives you a complete, independent second value, and there’s nothing that could be freed twice. Types like this implement the Copy trait, and assigning them copies instead of moving.

These types are Copy:

  • all the integer types, the float types, bool and char;
  • shared references, &T (Part 7);
  • tuples and arrays whose items are all Copy, such as (f64, f64) or [i32; 3].

These are not: String, Vec, Box and anything else that owns heap memory. A type that owns a resource can’t be Copy, because a bitwise copy would make a second owner.

Your own types can be Copy too, if every field is. You ask for it with derive. Part 10 covers structs properly; here we only need the idea:

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 1, y: 2 };
    let q = p;
    println!("{p:?} {q:?} sum {}", p.x + q.y);
}

It prints:

Point { x: 1, y: 2 } Point { x: 1, y: 2 } sum 3

Try the same with a field that owns memory, and the compiler refuses:

#[derive(Debug, Clone, Copy)]
struct Player {
    name: String,
    score: u32,
}

fn main() {
    let p = Player {
        name: String::from("Ana"),
        score: 10,
    };
    println!("{} {}", p.name, p.score);
}

It prints:

error[E0204]: the trait `Copy` cannot be implemented for this type
...
3 |     name: String,
  |     ------------ this field does not implement `Copy`

clone makes a real copy

When you do want two independent strings, ask for one with clone:

fn main() {
    let a = String::from("hello");
    let mut b = a.clone();
    b.push_str(" world");
    println!("a = {a}");
    println!("b = {b}");
}

It prints:

a = hello
b = hello world

clone allocates a new heap buffer and copies the bytes into it. Now there are two owners of two buffers, and each one frees its own.

let b = a; (move) let b = a.clone(); a moved b ptr hello one buffer, one owner a ptr hello b ptr hello two buffers, two owners

A move hands over the one buffer. A clone makes a second buffer, so each variable owns its own.

Rust makes you write .clone() so that copying heap memory is something you can see in the code. A let b = a never allocates. A .clone() usually does.

Moving into a function, and back out

Passing a value to a function is an assignment to its parameter, so it moves too:

fn shout(text: String) -> String {
    text.to_uppercase()
}

fn main() {
    let greeting = String::from("hello");
    let loud = shout(greeting);
    println!("{loud}");
    println!("{greeting}");
}

It prints:

error[E0382]: borrow of moved value: `greeting`
...
7 |     let loud = shout(greeting);
  |                      -------- value moved here
...
note: consider changing this parameter type in function `shout` to borrow instead if owning the value isn't necessary

shout took ownership of the string. When shout returned, text went out of scope and the original “hello” was dropped. The value that came back is a new string, the uppercase one.

The compiler’s note is the real fix, and it’s the subject of Part 7: let the function borrow the string instead of owning it. With only moves, the way to keep a value is to hand it back:

fn count_vowels(text: String) -> (String, usize) {
    let mut n = 0;
    for c in text.chars() {
        if "aeiou".contains(c) {
            n += 1;
        }
    }
    (text, n)
}

fn main() {
    let word = String::from("ownership");
    let (word, vowels) = count_vowels(word);
    println!("{word} has {vowels} vowels");
}

It prints:

ownership has 3 vowels

This works, and nobody writes Rust like this. Passing a value in and getting it back out is clumsy, and borrowing exists to remove it.

When Rust drops a value

A type can run code when it’s dropped by implementing the Drop trait. That lets us print a line at the exact moment each value goes away:

struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}

fn take(n: Noisy) {
    println!("take got {}", n.0);
}

fn main() {
    let first = Noisy("first");
    let second = Noisy("second");
    let third = Noisy("third");
    println!("made all three");

    take(second);
    println!("back in main");

    {
        let inner = Noisy("inner");
        println!("inside the block with {}", inner.0);
    }
    println!("after the block, still have {} and {}", first.0, third.0);
}

It prints:

made all three
take got second
drop second
back in main
inside the block with inner
drop inner
after the block, still have first and third
drop third
drop first

Noisy holds a &'static str, the type of a string literal like "first". Part 9 explains the 'static. For now, read it as “a piece of fixed text”.

Three things to notice:

  • second was dropped at the end of take, not at the end of main. Moving it into take made take‘s parameter the owner, and the owner decides when the value goes.
  • inner was dropped at the closing } of its block, the end of its scope.
  • third was dropped before first. Rust drops variables in the reverse order they were declared, so a value made later, which might depend on an earlier one, goes first.

Freeing a String‘s buffer is exactly this mechanism. String implements Drop, and its drop frees the heap bytes.

Worked example: taking a String out of a Vec

You have a list of names and want the first one. This is the line most people write first:

fn main() {
    let names = vec![String::from("Ana"), String::from("Ben")];
    let first = names[0];
    println!("{first}");
}

It prints:

error[E0507]: cannot move out of index of `Vec<String>`
 --> src/main.rs:3:17
  |
3 |     let first = names[0];
  |                 ^^^^^^^^ move occurs because value has type `String`, which does not implement the `Copy` trait

let first = names[0] would move the string out of the vector and leave a hole in it. The vector still believes it owns that slot, so when it was dropped, it would free the string a second time. Rust won’t allow a hole like that, so you have to say what you mean. There are four honest answers:

fn main() {
    let mut names = vec![
        String::from("Ana"),
        String::from("Ben"),
        String::from("Cai"),
    ];

    let looked_at = &names[0];
    println!("1. borrowed:  {looked_at}");

    let copied = names[0].clone();
    println!("2. cloned:    {copied}");

    let removed = names.remove(1);
    println!("3. removed:   {removed}, left {names:?}");

    let taken = std::mem::take(&mut names[0]);
    println!("4. taken:     {taken}, left {names:?}");
}

It prints:

1. borrowed:  Ana
2. cloned:    Ana
3. removed:   Ben, left ["Ana", "Cai"]
4. taken:     Ana, left ["", "Cai"]
  1. Borrow it with &names[0] when you only need to read it. This is the usual answer, and Part 7 explains it.
  2. Clone it when you need your own copy and the list keeps its own.
  3. Remove it when the list should give it up. remove shifts the later items down, so nothing is left behind.
  4. Take it with std::mem::take when you want the value and the slot must stay. It leaves an empty String in its place, so the vector still owns a valid value.

Worked example: a for loop that eats its vector

fn main() {
    let names = vec![String::from("Ana"), String::from("Ben")];
    for name in names {
        println!("hello, {name}");
    }
    println!("{} names", names.len());
}

It prints:

error[E0382]: borrow of moved value: `names`
...
3 |     for name in names {
  |                 ----- `names` moved due to this implicit call to `.into_iter()`
...
help: consider iterating over a slice of the `Vec<String>`'s content to avoid moving into the `for` loop
  |
3 |     for name in &names {

for name in names moves the whole vector into the loop, and each name owns one string in turn. When the loop ends, the vector is gone. That’s the right choice when you’re done with the list. When you still need it afterwards, loop over &names, as the compiler suggests:

fn main() {
    let names = vec![String::from("Ana"), String::from("Ben")];
    for name in &names {
        println!("hello, {name}");
    }
    println!("{} names", names.len());
}

It prints:

hello, Ana
hello, Ben
2 names

Tips and traps

  • .clone() to silence the compiler. It works, and while you’re learning it’s fine. But each clone of a String or Vec allocates and copies. When you add one, ask whether a borrow would do. In most code, it would.
  • “value moved here, in previous iteration of loop.” You moved a value inside a loop. The first time round it moved, so the second time round there’s nothing left to move. Clone inside the loop, or move it after the loop ends.
  • A move is not slow. let b = a on a String copies 24 bytes, whatever the length of the text. Moving a Vec of a million items copies the same 24 bytes.
  • Integers never move. If a program with i32 or f64 values compiles where a String version doesn’t, Copy is the reason.
  • Shadowing isn’t moving. let s = s.trim().to_string(); makes a new s that hides the old one. The old one is still dropped at the end of the scope.
  • Read the help: lines. Rust’s errors often name the fix, like &names in the loop example. Read them before you change anything.

Every value has exactly one owner. When the owner goes away, so does the value.

Exercises

Exercise 1. Without running it, decide whether this compiles, and if so what it prints:

let a = [1, 2, 3];
let b = a;
println!("{a:?} {b:?}");

Exercise 2. Fix this program so it prints 5 letters in hello. Don’t use clone, and don’t change the line in main that prints.

fn letters(s: String) -> usize {
    s.len()
}

fn main() {
    let word = String::from("hello");
    let n = letters(word);
    println!("{n} letters in {word}");
}

It prints:

error[E0382]: borrow of moved value: `word`

Exercise 3. Using the Noisy type from above, predict the order of the three drop lines this prints:

fn main() {
    let a = Noisy("a");
    let b = Noisy("b");
    let c = b;
    let d = Noisy("d");
    drop(a);
    println!("end of main");
}
Answers

1. It compiles. An array of i32 is Copy, because every item is Copy, so let b = a copies all three numbers:

fn main() {
    let a = [1, 2, 3];
    let b = a;
    println!("{a:?} {b:?}");
}

It prints:

[1, 2, 3] [1, 2, 3]

2. Hand the string back along with the count, the same way count_vowels did. In Part 7 we’ll fix it properly with a borrow.

fn letters(s: String) -> (String, usize) {
    let n = s.len();
    (s, n)
}

fn main() {
    let word = String::from("hello");
    let (word, n) = letters(word);
    println!("{n} letters in {word}");
}

It prints:

5 letters in hello

3. drop(a) drops a at once. std::mem::drop is an ordinary function that takes ownership and does nothing, so its parameter goes out of scope as it returns. Then, at the end of main, the rest are dropped in reverse order of declaration: d, then c. b was moved into c, so it isn’t dropped on its own.

struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}

fn main() {
    let a = Noisy("a");
    let b = Noisy("b");
    let c = b;
    let d = Noisy("d");
    drop(a);
    println!("end of main");
    println!("still here: {} {}", c.0, d.0);
}

We added the last line so that the compiler doesn’t warn that c and d are never used. It doesn’t change the order.

It prints:

drop a
end of main
still here: b d
drop d
drop b

The value that c owns was made as Noisy("b"), so its drop prints b.

What’s next

Moving a value into a function every time you want to read it doesn’t scale. In Part 7, we’ll lend values out instead: & for reading, &mut for changing, and the one rule that keeps both safe.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.