liveBook · Manning

Copy trait

As explained in Rust in Action: Systems programming concepts and techniques

Copy is a Rust marker trait whose implementation permits values of a type to be implicitly duplicated rather than moved.

Copy is a Rust marker trait that gives a type copy semantics. When ownership would otherwise move into another scope or function, Rust implicitly duplicates the value instead, leaving the original usable. section 4.1.2 section 4.5.3

Primitive values versus structs

An integer can be passed to `use_value(a)` and printed afterward because `i32` implements `Copy`. A `CubeSat` value does not behave that way automatically: passing it to an ownership-taking function moves it, so using it again produces a moved-value error. section 4.1.2 section 4.1.1

Listing 4.5 The copy semantics of Rust’s primitive types
 fn use_value(_val: i32) {     #1
 }
 
 fn main() {
   let a = 123 ;
   use_value(a);
 
   println!("{}", a);          #2
 
 }

Compare the short function call with the later print to see how Copy permits the original integer to remain accessible. section 4.1.2

Use Copy with these distinctions in mind:

  • Derive `Copy` and `Clone` for structs or enums whose fields and variants support Copy, as with a `CubeSat { id: u64 }` and a simple status enum. section 4.5.3
  • Treat Copy as implicit, fast, cheap, identical duplication; treat Clone as explicit duplication through `.clone()`, which may be slower or define different behavior. section 4.5.3
  • Avoid assuming every useful type should implement Copy: exact duplication can be costly for large values and unsafe for ownership-bearing references. section 4.5.3
  • Use `Clone` or `Copy` pragmatically when duplication helps resolve an ownership or borrow-checker impasse. section 4.6

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains implicit duplication, contrasts Clone, identifies limitations, and demonstrates deriving or manually implementing the traits.
Examples
Uses integers, a CubeSat struct, a status enum, compiler errors, and paired Copy-versus-move listings.
What it assumes
Builds from zero on ownership movement while relating Copy to borrowing and value lifetimes.
What you can do after
Apply Copy by recognizing implicit duplication, diagnosing moved-value errors, and deriving or implementing Copy for suitable types.
How it connects
Connects Copy with ownership, move semantics, borrowing, Clone, the borrow checker, and reference counting.

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 Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.