Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 132 ยท Ownership and Borrowing

Ownership

Understand Rust ownership from the ground up - stack and heap, the three ownership rules, moves, Copy versus Clone, drop at scope end and ownership in function calls.

Ownership is the idea that makes Rust different from every mainstream language. It is how Rust manages memory without a garbage collector (like Java, Go or Python) and without asking you to call free yourself (like C). You write ordinary-looking code, and the compiler checks a small set of rules at compile time. If your program follows the rules, memory is released exactly once, exactly when it is no longer needed, and no part of the program can touch memory that has already been freed.

Many learners find ownership hard at first, mostly because it asks you to think about who is responsible for a value. This lesson builds the idea slowly: where values live, the three rules, what a "move" is, why some types are copied instead, what happens at the end of a scope, and how all of this works when you pass values to functions. The next lesson shows how to let other code use a value without taking it over.

Stack and heap in two minutes

A running program stores data in two main places.

  • The stack is fast, tidy memory. Each function call gets a block (a "frame") for its local variables, and the block disappears when the function returns. Everything on the stack must have a size known at compile time: integers, booleans, char, tuples and arrays of those.
  • The heap is a big pool of memory for data whose size is only known at run time or that must outlive the function that created it: the text in a String, the elements of a Vec. To use it you ask for a chunk and get back a pointer; later you must give it back.

A String is both. The small part, called its header, lives on the stack and holds three machine words: a pointer to the heap, the length and the capacity. The characters live on the heap.

Rust The stack part of a String is small and fixed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

On a 64-bit machine the header is 24 bytes whatever the text length (three 8-byte words). The text itself is separate. Languages with a garbage collector periodically search for heap memory nobody uses and free it. C makes you free it by hand and trusts you not to forget or free twice. Rust's answer is ownership.

The three rules

Memorize these; everything else in this chapter follows from them.

  1. Every value has exactly one owner, a variable (or a field, or an element of a collection).
  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 released).

Rule 3 is the heart of it. A scope is the region of code where a variable is valid, usually a block between { and }. When the closing brace is reached, Rust automatically runs the cleanup for every variable declared in the block, in reverse order. You never write free. (This idea is called RAII; see Drop and RAII.)

You can watch this happen by giving a type a Drop implementation that prints a message. Drop::drop is the function Rust calls when a value is cleaned up:

Rust Drop runs at the end of the scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The output shows b (inner) being dropped as soon as the inner block ends, and at the end of main the remaining variables are dropped in the reverse order of creation: c first, then a. This predictability is what makes Rust usable for files, locks and network connections too, not only memory.

Moves

What does rule 2 mean in practice? Look at what happens when you assign a String to another variable:

Rust Assigning a String moves it (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This does not compile. The key lines:

TEXT
error[E0382]: borrow of moved value: `first`
 --> main.rs:6:16
  |
2 |     let first = String::from("hello");
  |         ----- move occurs because `first` has type `String`, which does not implement the `Copy` trait
3 |     let second = first;
  |                  ----- value moved here
...
6 |     println!("{first}");
  |                ^^^^^ value borrowed here after move

When you write let second = first;, the ownership moves from first to second. The 24-byte header is copied to the new variable, but the old variable is now considered uninitialized, and using it is an error. Why does Rust go to this trouble? Imagine it did allow both variables to use the same heap text. At the end of the scope both would try to free it. That is a double free, a classic memory-safety bug and a favorite of attackers. Rust prevents it by making sure there is only ever one owner to do the freeing.

Compare the alternatives. A shallow copy (the pointer only) makes two owners; a deep copy (pointer and text) is safe but costly. Rust's move is a shallow copy plus invalidating the old name, so you get the cheap copy and the safety.

Moving into functions

Passing a value to a function is a move too, for exactly the same reason: the parameter is a new owner.

Rust A function takes ownership

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

After consume(message) the variable message is gone. If you try to print it afterwards, you get the same E0382 error as before. A function can also give ownership back by returning the value:

Rust Taking ownership and giving it back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Passing a value in and returning it works, but it quickly becomes clumsy: imagine a function that should merely read a string and give it back untouched. Rust solves this with references, which let a function borrow a value without owning it. That is the entire topic of References and Borrowing. As a rule of thumb: take ownership (String) only when the function needs to keep or consume the value, and borrow (&str) when it just needs to look.

Copy: types that are not moved

Look at this code, which looks just like the failing one but uses integers:

Rust Integers are copied, not moved

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This compiles, and both variables remain usable. The reason is the Copy trait. A type that implements Copy is simple enough that duplicating its bytes is a complete, safe copy; there is no heap data and nothing to free. Assigning such a value copies it, and both variables own independent values.

Copy is implemented for:

  • all integer and floating-point types, bool, char;
  • shared references &T (a reference is just a pointer);
  • tuples and arrays whose elements are all Copy;
  • your own structs and enums, if you ask for it with #[derive(Clone, Copy)] and all their fields are Copy.

A type that owns heap data (String, Vec, Box) can never be Copy; the compiler rejects it. A type that implements Drop cannot be Copy either.

Clone: copying on purpose

If you really want a second, independent String, say so explicitly with .clone():

Rust clone makes a deep copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

clone allocates new heap memory and copies the text, so afterwards there are two owners of two separate buffers. The call is visible in the source on purpose: Rust makes expensive operations explicit, so when you read a program you can spot where memory is allocated. Copy is silent and cheap (a few bytes); Clone is explicit and may be expensive.

Copy Clone
How it happens Automatically on assignment and calls Only when you call .clone()
Cost Always a cheap bit-for-bit copy Anything, including a full deep copy
Types Plain data: numbers, char, bool, &T... Almost everything: String, Vec, your types with #[derive(Clone)]
Relationship Every Copy type is also Clone

Cloning is the easiest way to silence a borrow-checker error, and a perfectly fine one when you need two independent values. But do not add .clone() mindlessly: inside a hot loop it can mean thousands of hidden allocations. Often a reference is the right tool instead.

Ownership of fields and collections

The rules apply recursively. A struct owns its fields; when the struct is dropped, so are the fields. A Vec<String> owns its strings. Moving the struct moves all its fields along with it:

Rust Ownership of parts and wholes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Moving a field out of a struct (let name = ada.name;) is allowed and leaves the struct partially moved: the remaining fields are still usable, but the struct as a whole is not. Moving an element out of a Vec by index is not allowed (let s = team[0]; gives error E0507, "cannot move out of index of Vec<String>") because that would leave a hole in the vector. You would write team[0].clone(), take it by team.remove(0), or borrow it with &team[0].

Why this design?

Ownership gives Rust a combination that is normally mutually exclusive:

  • No garbage collector pauses. Memory is freed at fixed points known at compile time, so latency is predictable.
  • No manual freeing. You cannot forget to free, and you cannot free twice.
  • No use-after-free and no dangling pointers, because the compiler proves no variable outlives its value.
  • Resources beyond memory (files, sockets, mutex guards) are released with the same mechanism, so they are closed even if the function returns early or panics.

The price is that you must learn to think in terms of owners. Most of the time you will work with the rules rather than against them: pass references when you only need to look, move values when handing over responsibility, and clone when you truly need a second copy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is one of Rust's three ownership rules?

    The rules are: each value has one owner, there is only one owner at a time, and the value is dropped when the owner goes out of scope.
  2. 2. What happens here?

    let a = String::from("x"); let b = a; println!("{a}");

    String does not implement Copy, so assigning it moves ownership. Using a afterwards is a compile error.
  3. 3. Why does let y = x; leave x usable when x is an i32?

    i32 is Copy. Assignment duplicates the bits, and both variables own independent values.
  4. 4. In what order are local variables dropped at the end of a scope?

    Locals are dropped in reverse order of creation, last declared first.
  5. 5. A function has the signature fn print_it(s: String). After print_it(my_string); what is true?

    Passing a non-Copy value by value moves it. To keep using it, pass a reference (&my_string) or clone it.

Summary

  • Values on the stack have a known size; data such as String text and Vec elements lives on the heap, with a small header on the stack.
  • The ownership rules: one owner per value, one owner at a time, the value is dropped when its owner goes out of scope.
  • Assigning or passing a non-Copy value moves it; the old variable cannot be used afterwards (E0382). This prevents double frees.
  • Copy types (numbers, bool, char, &T, and tuples or arrays of them) are duplicated silently; .clone() makes explicit, possibly expensive copies.
  • Locals are dropped in reverse order of declaration; implement Drop to see or customize cleanup.
  • Moving a field out of a struct leaves it partially moved; you cannot move out of a Vec by index.
  • To use a value without taking it, borrow it: that is the next lesson.

Next: References and Borrowing