typestar

Clone and Copy in Rust

Copy types duplicate silently; everything else moves unless you ask for a clone.

fn main() {
    let a = 7;
    let b = a;
    println!("{a} and {b} both fine");

    let owned = String::from("tours");
    let copy = owned.clone();
    println!("{owned} / {copy}");

    let moved = owned;
    println!("{moved} now holds it");

    let list = vec![1, 2, 3];
    let same_again = list.clone();
    println!("{:?} {:?}", list, same_again);
}

How it works

  1. Integers are Copy, so assignment leaves the original usable.
  2. A String moves, and clone is the explicit deep copy.
  3. clone costs an allocation — that is why it is not implicit.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
315
Tokens
95
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 63 seconds.

Type this snippet

Step 2 of 3 in Move & clone, step 2 of 15 in Ownership & borrowing.

← Previous Next →