liveBook · Manning

Copy trait

As explained in Learn Rust in a Month of Lunches

A copy type is a Rust type whose values can be duplicated implicitly by copying their bits rather than transferring ownership.

A type that implements Rust’s Copy trait is copied automatically when its value is passed to a function. The function gets the data, and the original value can still be used. Simple types such as integers, floats, booleans, and char are Copy types. This is called *copy semantics*, rather than *move semantics*. section 2.8

fn prints_number(number: i32) {    #1
    println!("{}", number);
}
 
fn main() {
    let my_number = 8;
    prints_number(my_number);      #2
    prints_number(my_number);      #3
}

The i32 value can be passed to prints_number twice: each call gets a copy. section 2.8

String behaves differently. It does not implement Copy, so passing it to a function that takes ownership moves the value. Trying to pass the same String again produces a “use of moved value” error. That error points to both the first call, where the move happened, and the second call, where the value is no longer available. section 2.8

error[E0382]: use of moved value: `country`
 --> src\main.rs:4:20
  |
2 |     let country = String::from("Kiribati");
  |         ------- move occurs because `country` 
  has type `std::string::String`, which does not implement the `Copy` trait
3 |     prints_country(country);
  |                    ------- value moved here
4 |     prints_country(country);
  |                    ^^^^^^^ value used here after move

The compiler explicitly says that String does not implement the Copy trait. section 2.8

If you need another String value, call .clone() explicitly. If the function only needs to read the String, pass a reference instead of repeatedly cloning it. To check whether a type is Copy, look for Copy under “Trait Implementations” in its documentation. section 2.8

Think of a Copy value like a cheap paperclip: handing one over is simple enough that you need not track who owns the original. section 2.10

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through repeated calls, trait documentation, and a moved-value error; stops short of implementing Copy.
Examples
Contrasts repeated calls with an i32 against a moved String, then shows cloning and passing a reference.
What it assumes
Builds on ownership, references, and String while explaining copy versus move through small examples.
What you can do after
Diagnose/debug with it by recognizing why repeated use works for a Copy value but fails after moving a String.
How it connects
Connects ownership and move semantics to function arguments, String, Clone, and borrowing.

Also explained in

Compare how 3 books explain Copy trait →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.