In Rust, let b = a; moves ownership by default, and a can no longer be used afterwards. Only types that implement Copy, such as integers, are bitwise-copied and leave the original usable. Duplicating heap data takes an explicit clone() call.

In Java or Python, assignment copies a reference, and both variables point to the same object. Rust uses the same assignment syntax but invalidates the original variable. I wanted to work out how that difference surfaces as compile errors, and which types are copied and which are moved. Every example below was compiled with rustc 1.94.1, edition 2021, and the ones that compile were also run.

Move

Assigning a String to another variable and then using the original does not compile.

fn main() {
    let original = String::from("hello");
    let moved = original;
    println!("{moved}");
    println!("{original}");
}
error[E0382]: borrow of moved value: `original`
 --> move_assign.rs:5:16
  |
2 |     let original = String::from("hello");
  |         -------- move occurs because `original` has type `String`, which does not implement the `Copy` trait
3 |     let moved = original;
  |                 -------- value moved here
4 |     println!("{moved}");
5 |     println!("{original}");
  |                ^^^^^^^^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let moved = original.clone();
  |                         ++++++++

The error message states the cause. String does not implement Copy, so on line 3 the value moved into moved, and line 5 uses the value after the move. The word “borrow” in the message appears because println! reads the value through a reference.

To see what happens in memory during a move, I compared the heap address before and after the move and printed the size of a String itself.

fn main() {
    let original = String::from("hello");
    let heap_before = original.as_ptr();
    let moved = original;
    println!("same heap buffer: {}", heap_before == moved.as_ptr());
    println!("size_of::<String>() = {}", std::mem::size_of::<String>());

    let cloned = moved.clone();
    println!("clone shares buffer: {}", moved.as_ptr() == cloned.as_ptr());
}
same heap buffer: true
size_of::<String>() = 24
clone shares buffer: false
Memory for move and clone: move copies the 24 stack bytes, clone allocates a new heap bufferlet moved = original;stackheaporiginalptrlen 5cap 5invalid (moved)movedptrlen 5cap 5hellosame bufferlet cloned = moved.clone();movedptrlen 5cap 5helloclonedptrlen 5cap 5hellonew buffer allocated

A String value consists of a pointer to its heap buffer, a length, and a capacity, which take 24 bytes on a 64-bit target. After a move, those 24 bytes become the value of the new variable, and the string data on the heap stays where it is. That is why moved points to the same heap address as before. The Copy documentation explains that both a copy and a move can be a bitwise copy in memory; the only difference is whether the original can be used after the assignment.

Rust invalidates the original because of drop. If two variables pointed to the same heap buffer and both were dropped at the end of their scopes, the buffer would be freed twice. A move keeps a single owner, so drop runs only once.

Function Arguments and Return Values

Passing a value as a function argument is a move, just like assignment.

fn consume(text: String) {
    println!("consume {text}");
}

fn main() {
    let message = String::from("hello");
    consume(message);
    println!("{message}");
}
error[E0382]: borrow of moved value: `message`
 --> move_fn.rs:8:16
  |
6 |     let message = String::from("hello");
  |         ------- move occurs because `message` has type `String`, which does not implement the `Copy` trait
7 |     consume(message);
  |             ------- value moved here
8 |     println!("{message}");
  |                ^^^^^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `consume` to borrow instead if owning the value isn't necessary
 --> move_fn.rs:1:18
  |
1 | fn consume(text: String) {
  |    -------       ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
7 |     consume(message.clone());
  |                    ++++++++

Ownership passes to the parameter text of consume, and the string is dropped at the end of consume, where the scope of text ends. The caller no longer holds the value.

Moving inside a loop fails the same way on the second iteration. The compiler points out that the value was already moved in a previous iteration.

// consume is the same as above
fn main() {
    let message = String::from("hello");
    for _ in 0..2 {
        consume(message);
    }
}
error[E0382]: use of moved value: `message`
 --> loop_move.rs:8:17
  |
6 |     let message = String::from("hello");
  |         ------- move occurs because `message` has type `String`, which does not implement the `Copy` trait
7 |     for _ in 0..2 {
  |     ------------- inside of this loop
8 |         consume(message);
  |                 ^^^^^^^ value moved here, in previous iteration of loop

Returning a value moves ownership back to the caller. A function that takes a value, modifies it, and hands it back looks like this.

fn append_suffix(mut text: String) -> String {
    text.push_str(" world");
    text
}

fn main() {
    let message = String::from("hello");
    let message = append_suffix(message);
    println!("{message}");
}
hello world

Passing a value in and getting it back on every call became tedious to me as the number of returned values grew. As the note in the error above suggests, a function that does not need ownership should take a reference instead. References and borrowing are the topic of the next post in the series.

Partial Moves

You can move a single field out of a struct. The fields that were not moved stay usable, but the struct as a whole does not.

struct User {
    name: String,
    age: u32,
}

fn main() {
    let user = User { name: String::from("alice"), age: 30 };
    let name = user.name;
    println!("{name} {}", user.age);
    let _whole = user;
}
error[E0382]: use of partially moved value: `user`
  --> partial.rs:10:18
   |
 8 |     let name = user.name;
   |                --------- value partially moved here
 9 |     println!("{name} {}", user.age);
10 |     let _whole = user;
   |                  ^^^^ value used here after partial move
   |
   = note: partial move occurs because `user.name` has type `String`, which does not implement the `Copy` trait

user.age on line 9 is accepted, because age was not moved. Line 10 tries to move all of user, which is missing name, so it is rejected.

Pattern matching also moves when it binds a value. if let Some(name) moves the String inside the Option into name.

fn main() {
    let nickname: Option<String> = Some(String::from("ally"));
    if let Some(name) = nickname {
        println!("hi {name}");
    }
    println!("{nickname:?}");
}
error[E0382]: borrow of partially moved value: `nickname`
 --> match_move.rs:6:16
  |
3 |     if let Some(name) = nickname {
  |                 ---- value partially moved here
...
6 |     println!("{nickname:?}");
  |                ^^^^^^^^ value borrowed here after partial move
  |
  = note: partial move occurs because value has type `String`, which does not implement the `Copy` trait
help: borrow this binding in the pattern to avoid moving the value
  |
3 |     if let Some(ref name) = nickname {
  |                 +++

Fields cannot be moved out of a struct that implements Drop.

struct Session {
    token: String,
}

impl Drop for Session {
    fn drop(&mut self) {
        println!("drop session");
    }
}

fn main() {
    let session = Session { token: String::from("abc") };
    let token = session.token;
    println!("{token}");
}
error[E0509]: cannot move out of type `Session`, which implements the `Drop` trait
  --> partial_drop.rs:13:17
   |
13 |     let token = session.token;
   |                 ^^^^^^^^^^^^^
   |                 |
   |                 cannot move out of here
   |                 move occurs because `session.token` has type `String`, which does not implement the `Copy` trait

When session goes out of scope, its drop method runs, and that method may use the fields. rustc --explain E0509 explains that drop cannot run on a struct whose fields have been moved out. So a type that implements Drop is treated as a single unit whose fields cannot be moved. The Rust Reference likewise allows moving out of a field only when the containing type does not implement Drop.

Copy

An integer stays usable after assignment.

fn main() {
    let count = 5;
    let copied = count;
    println!("{count} {copied}");
}
5 5

This works because i32 implements Copy. A Copy type is bitwise-copied on assignment or when passed as an argument, and the original remains valid. Integers, floating-point numbers, bool, char, and shared references &T are Copy, and so are tuples and arrays whose elements are all Copy.

For your own types, add Copy with #[derive(Clone, Copy)]. Clone is a supertrait of Copy, so both have to be listed.

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

fn shift(mut point: Point) -> Point {
    point.x += 1;
    point.y += 1;
    point
}

fn main() {
    let origin = Point { x: 0, y: 0 };
    let shifted = shift(origin);
    println!("{origin:?} {shifted:?}");
}
Point { x: 0, y: 0 } Point { x: 1, y: 1 }

shift received a copy and modified it; origin is unchanged after the call.

To implement Copy, every field must be Copy. Adding Copy to a struct with a String field fails with E0204.

#[derive(Clone, Copy)]
struct Account {
    id: u64,
    owner: String,
}
error[E0204]: the trait `Copy` cannot be implemented for this type
 --> copy_e0204.rs:1:17
  |
1 | #[derive(Clone, Copy)]
  |                 ^^^^
...
4 |     owner: String,
  |     ------------- this field does not implement `Copy`

Even when every field is Copy, a type that implements Drop causes E0184.

#[derive(Clone, Copy)]
struct Handle {
    id: u32,
}

impl Drop for Handle {
    fn drop(&mut self) {
        println!("drop {}", self.id);
    }
}
error[E0184]: the trait `Copy` cannot be implemented for this type; the type has a destructor
 --> copy_drop.rs:1:17
  |
1 | #[derive(Clone, Copy)]
  |                 ^^^^ `Copy` not allowed on types with destructors

The Copy documentation uses String as the example. A bitwise copy of a String copies the pointer, length, and capacity but not the heap buffer, so both values would be responsible for freeing the same buffer and it would be freed twice. Generalizing from that, the documentation says a type implementing Drop manages a resource that does not fit in its own size_of::<T> bytes, so it cannot be Copy. A mutable reference &mut T is not Copy either: copying it would create two mutable references to the same value.

The behavior of Copy cannot be overridden; it is always a bitwise copy. The documentation recommends implementing Copy whenever a type can, but also notes that Copy is part of the type’s public API. If a field like String is added later, Copy has to go, and every caller that used the original after assignment stops compiling. For a type whose fields may change, I concluded it is safer to leave Copy off from the start.

Clone

clone() duplicates a value explicitly. Cloning a String or a Vec allocates a new heap buffer and copies the contents, which is why the earlier example printed clone shares buffer: false. For a Vec<String>, cloning allocates the outer buffer plus a new buffer for each String element.

The Clone documentation sums up the difference between the two traits. Copy is an implicit, inexpensive bitwise copy. Clone is always explicit, and its cost depends on the type; the clone method may run arbitrary code.

A cloned value has its own owner, separate from the original, so it is dropped separately. I checked this with a Drop implementation that prints a name.

#[derive(Clone)]
struct Buffer {
    name: String,
}

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

fn main() {
    let first = Buffer { name: String::from("first") };
    let moved = first;
    let mut cloned = moved.clone();
    cloned.name.push_str("-clone");
    println!("end of main");
}
end of main
drop first-clone
drop first

The value that moved from first to moved was dropped once, and the clone was dropped once on its own. Clone can be implemented together with Drop, because the clone holds its own resources and the frees do not overlap.

The String assignment and function-argument errors above both suggested adding .clone(). When the original and the copy each need to change independently, clone is the right choice. But adding clone only to silence the error when the value is only read means an allocation and a copy on every call. On a path that runs in a loop or on every request, that cost accumulates. The compiler’s own wording is “if the performance cost is acceptable”. In those cases I judged that passing a reference, as the note on the function-argument error suggests, should come first. Because clone() is visible in the code, a code review can find where duplication costs arise.

Wrapping Up

A move invalidates the original variable so that there is a single owner and drop runs once. A Copy type leaves the original intact, but only types with no resources to free can be Copy. Heap data is duplicated only through a clone() call, so the places where duplication costs arise are visible in the code. Unlike Java and Python, where assignment copies a reference and shares the object, in Rust the type decides what a single assignment means.

References