FAQ - Help and questions

What is the difference between move, Copy and Clone in Rust?

#ownership#basics#traitspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Assigning or passing a value moves it by default, and the old name can no longer be used. Types marked Copy, such as numbers and small plain structs, are copied bit for bit instead. Clone is an explicit method call that makes a duplicate and may allocate, so it shows up in the code.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Three different things can happen when you write let b = a;:

  • Move: the default. b now owns the value and a is unusable. Nothing is copied at run time, only ownership changes.
  • Copy: for types that implement the Copy trait. Both a and b stay valid. Only types that are trivial to duplicate can be Copy: numbers, bool, char, shared references, and your own structs made only of such things.
  • Clone: not automatic. You call .clone() and get an independent duplicate, which for a String or Vec allocates and copies the contents.
src/main.rsrust
#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

#[derive(Debug, Clone)]
struct Player {
    name: String,
    at: Point,
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = a; // Copy: both stay usable
    println!("{a:?} {b:?}");

    let p = Player { name: "Ada".into(), at: a };
    let q = p.clone(); // Clone: an explicit, possibly costly copy
    let r = p; // move: `p` can no longer be used
    println!("{} {} {}", q.name, r.name, r.at.x);
}
text
Point { x: 1, y: 2 } Point { x: 1, y: 2 }
Ada Ada 1

How to decide#

  • You need the original afterwards: pass a reference (&value) if the receiver only reads, or .clone() if it must own its own copy.
  • Your small struct is only numbers: add #[derive(Clone, Copy)] and it behaves like a number.
  • A type that owns heap memory or a resource (String, Vec, a file handle) cannot be Copy, because two owners would free the same memory.

Common mistakes#

  • Cloning to silence a borrow checker error without asking why. Sometimes it is right, but often the function should take a reference.
  • Expecting #[derive(Copy)] to work on a struct that contains a String. It does not compile.

Why does println!("{name}") not move name?#

Formatting macros take their arguments by reference. They read the value and leave it where it is.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet