Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 132 ยท Ownership and Borrowing

Copy, Clone and Move Semantics

Understand Rust Copy and Clone, when assignment moves or copies, what cloning costs, and how mem::swap, replace and take move values out of borrowed places.

In Ownership you learned that let b = a; moves a String: a is no longer usable. But the same line with integers leaves both usable. What is the difference? It is a single trait, Copy. This lesson explains the difference between moving, copying and cloning, which of your own types should be Copy, what .clone() really costs, and a set of standard-library tools (mem::swap, mem::replace, mem::take) for the awkward situation of moving a value out of something you only borrow.

Move is the default

Every assignment, function argument and return in Rust copies the value's bytes to the new place. For a String those bytes are just the pointer, length and capacity (24 bytes), not the text on the heap. After that shallow bit-copy, two owners would exist and both would free the same heap buffer. To prevent a double free, the compiler marks the source as unusable. That is a move.

Rust Use after move (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.

TEXT
error[E0382]: borrow of moved value: `a`
 --> 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} {b}");
  |                ^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let b = a.clone();
  |              ++++++++

Notice the first label: the compiler tells you the reason, "which does not implement the Copy trait". Moves cost nothing at run time (no heap work happens), and the check happens entirely at compile time.

Copy: duplicating is trivial

A type can implement Copy when duplicating it is just copying bytes and nothing else needs to happen. Then assignment copies and the source stays valid:

Rust Copy types stay usable

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 standard Copy types are: all integer and float types, bool, char, shared references &T, raw pointers, function pointers, and tuples/arrays made only of Copy types. Not Copy: String, Vec, Box, and &mut T (two mutable references would break the borrowing rule).

The rules for Copy

  • A type may be Copy only if all its fields are Copy.
  • A type with a Drop implementation (custom cleanup) can never be Copy: duplicating bytes would run the cleanup twice.
  • Copy requires Clone as a supertrait, so you derive both together.
Rust Deriving Copy for your own types

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.

If one field is not Copy, the derive is rejected at compile time:

Rust Deriving Copy with a String field (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.

TEXT
error[E0204]: the trait `Copy` cannot be implemented for this type
 --> main.rs:2:8
  |
1 | #[derive(Clone, Copy)]
  |                 ---- in this derive macro expansion
2 | struct User {
  |        ^^^^
3 |     id: u32,
4 |     name: String,
  |     ------------ this field does not implement `Copy`

Should my type be Copy?

Small value-like types (points, colours, ids, simple enums, small flag structs) usually should be Copy; it makes them painless to use. Be careful with big arrays ([u8; 4096] is Copy and gets bit-copied on every pass!) and with types that may later gain a heap field: adding Copy is easy, removing it later breaks every caller. A good rule of thumb is up to roughly 16 to 32 bytes of plain data.

Clone: explicit, possibly expensive duplication

Clone is for values that cannot be copied bit-for-bit. .clone() is an ordinary method that does whatever is needed to make an independent duplicate, such as allocating a new buffer and copying the text:

Rust clone makes an independent 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.

Cloning a Vec<Vec<i32>> allocates once for the outer vector and once per inner vector. In Rust, every .clone() call is visible in the source, so you can search for the costly spots. Copy never shows up as a call at all, because copying is always cheap.

Counting clones

Here is a type that reports each time it is cloned, so you can see exactly when the compiler calls clone for you (never) and when you do:

Rust Watching clone calls

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 on references

Calling .clone() on a &String gives a String, because method lookup finds String::clone first. But on a &T where T is not Clone, the call quietly clones the reference and gives you another &T. This is a real source of confusion; if you expect an owned value, annotate the type: let owned: T = reference.clone();, and the compiler will tell you if it cannot.

Do not reach for .clone() just to silence a borrow-checker error. Often it fixes the symptom while making the program slower, and sometimes it hides a bug where you wanted two parts of the program to share one value. First try borrowing, restructuring, or moving ownership. See The Borrow Checker in Practice.

Moves into functions, loops and closures

Passing by value moves. If the callee returns the value, you can take it back, but borrowing is usually cleaner:

Rust Moving into a function and getting 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.

for w in words consumes the vector. Use for w in &words to borrow instead.

A preview: move in closures

A closure that uses a variable by value takes ownership of it when you write move. This is vital for threads (see Threads) and covered fully in Closures. Copy types are copied into the closure, so the original stays usable; others are moved:

Rust move closures copy or move captures

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 out of borrowed content

The most baffling errors for newcomers appear when you try to take ownership of something that lives inside a borrowed value, a vector or a struct behind a reference. You cannot leave a hole in the original, so Rust says no (E0507 or E0508).

Rust Moving out of a Vec by index (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.

TEXT
error[E0507]: cannot move out of index of `Vec<String>`
 --> main.rs:4:17
  |
4 |     let first = names[0];
  |                 ^^^^^^^^ move occurs because value has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
4 |     let first = &names[0];
  |                 +
help: consider cloning the value if the performance cost is acceptable
  |
4 |     let first = names[0].clone();
  |                         ++++++++

If you moved the string out, the vector would still believe it owned a (now invalid) element and drop it later: a double free. Pick the right remedy:

  1. Borrow if reading is enough: &names[0].
  2. Clone if you need your own copy: names[0].clone().
  3. Take it out of the Vec properly, which restructures the vector: remove, swap_remove, pop, drain, or into_iter.
  4. Swap something in its place with mem::replace or mem::take (next section).
Rust Taking ownership out of a Vec the right way

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 same restriction applies to struct fields behind a & or &mut reference:

Rust Moving a field out of a borrowed struct (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.

TEXT
error[E0507]: cannot move out of `p.name` which is behind a shared reference
 --> main.rs:6:5
  |
6 |     p.name
  |     ^^^^^^ move occurs because `p.name` has type `String`, which does not implement the `Copy` trait
  |
help: consider cloning the value if the performance cost is acceptable
  |
6 |     p.name.clone()
  |           ++++++++

Fix: return p.name.clone(), return &str, or take Profile by value if the function is meant to consume it.

mem::swap, mem::replace and mem::take

When you have a &mut T and need to move the current value out, you must leave something valid behind. The std::mem functions do exactly that, safely and without cloning:

  • mem::swap(&mut a, &mut b) exchanges two values.
  • mem::replace(&mut slot, new) puts new in and returns the old value.
  • mem::take(&mut slot) replaces the value with Default::default() and returns the old one (an empty String, empty Vec, None, 0...).
Rust swap, replace and take

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.

A state machine that consumes its state

A very common use is a type whose method needs the old state by value to compute the new state. With only &mut self, plain assignment cannot do it; mem::replace can:

Rust Transitioning a state held behind &mut self

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.

mem::replace is a cheap pointer-sized operation. For a type with no sensible default, replace with any placeholder variant (Job::Finished(0) here), which gets overwritten right away.

Clone-on-write and cheap sharing

If clones are too expensive and you need many owners of the same data, consider Rc<T> or Arc<T>: cloning them only bumps a counter (Rc, Arc and Shared Ownership). std::borrow::Cow<str> borrows when it can and clones only when you modify.

Rust Cow: clone only when needed

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.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does let b = a; do when a is a String?

    Assignment copies the 24-byte handle and marks a as moved. There is no heap work, and no automatic clone.
  2. 2. Which type can derive Copy?

    All fields must be Copy. String and Vec own heap memory, and &mut references are never Copy.
  3. 3. What is true about .clone() in Rust?

    Clone is explicit and its cost depends on the type. The compiler never inserts clones for you.
  4. 4. You have slot: &mut Option<String> and want its current value as an owned Option, leaving None behind. What do you use?

    Option::take (like mem::take) moves the value out and leaves the default, None, in its place.
  5. 5. Why is let first = names[0]; rejected when names is a Vec<String>?

    That is E0507. Borrow it with &names[0], clone it, or remove it from the vector.

Summary

  • Assignment, arguments and returns move by default: a shallow byte copy, then the source is invalid. It is free at run time and checked at compile time.
  • Copy types (numbers, bool, char, &T, tuples and arrays of Copy types, your own all-Copy types) are duplicated implicitly; derive Clone and Copy together for small value types.
  • Clone is explicit duplication that may allocate. Every .clone() is visible in code; do not use it just to appease the borrow checker.
  • You cannot move out of a Vec index or a borrowed struct field (E0507). Borrow, clone, or take the item properly with pop, remove, swap_remove, into_iter.
  • mem::swap, mem::replace and mem::take (and Option::take) move a value out of a &mut place by leaving a valid one behind.
  • Use Rc/Arc for cheap shared ownership and Cow to clone only when modifying.

Next: Lifetimes