liveBook · Manning

Copy trait

As explained in Refactoring to Rust

The Copy trait marks Rust types whose values can be duplicated implicitly without moving ownership from the original binding.

The Copy trait marks Rust types whose values can be duplicated implicitly, allowing the original binding to remain usable instead of transferring ownership. It matters when a value must be passed to a function more than once. section 2.1

Admiring the same artwork twice

An artwork containing a String is passed to admire_art twice. The first call moves art1 into the function, so the second call fails with “use of moved value”; the diagnostic notes that Artwork does not implement Copy. section 2.1

Listing 2.5 A program attempting to admire the same art twice
struct Artwork {
  name: String,
}

fn admire_art(art: Artwork) {
  println!("Wow, {} really makes you think.", art.name);
}

fn main() {
  let art1 = Artwork { name: "The Ordeal of Owain".to_string() };

  admire_art(art1);
  admire_art(art1);
}

Inspect the failing program that attempts to pass the same artwork to admire_art twice. section 2.1

$ cargo run
error[E0382]: use of moved value: `art1`
  --> src/main.rs:11:16
   |
8  |     let art1 = Artwork {};
   |         ---- move occurs because `art1` has type `Artwork`, which
   |              does not implement the `Copy` trait
9  |
10 |     admire_art(art1);
   |                ---- value moved here
11 |     admire_art(art1);
   |                ^^^^ value used here after move

error: aborting due to previous error; 1 warning emitted

Read the compiler diagnostic identifying the move, the later invalid use, and the missing Copy implementation. section 2.1

How Refactoring to Rust covers it

How deep it goes
Defines Copy through a concrete compiler error but stops short of implementation rules or trait derivation.
Examples
Uses an art museum program, an Artwork struct containing String, two function calls, and the resulting E0382 diagnostic.
What it assumes
Introduces ownership through a beginner-oriented function-call example and briefly contrasts Rust’s memory management with other languages.
What you can do after
Evaluate why a repeated value use fails after a function call that moves ownership.
How it connects
Connects Copy with ownership, moves, values, functions, compiler errors, and memory management.

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 Refactoring to Rust. The section links point to the parts of the book it draws on.