liveBook · Manning

Copy semantics

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

Copy semantics are value-transfer rules in which assigning or passing a value duplicates it while leaving the original usable.

Copy semantics describe value transfer in which assigning or passing a value duplicates it, leaving the original usable. In Rust, primitive types implement the Copy trait, so passing an integer to a function does not make the outer variable inaccessible. section 4.1.2

Compare copying with moving:

  • An i32 can be passed to use_value and then printed because the value was implicitly duplicated. section 4.1.2
  • A custom Demo value without Copy is moved into a function, so accessing it afterward causes an ownership error. section 4.1.2
  • A small tuple struct such as Q7 can opt into cheap implicit duplication with #[derive(Copy)], changing it from move semantics to copy semantics. section 5.5
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
 
 }

Shows a primitive integer surviving a function call because its Copy implementation duplicates the value. section 4.1.2

Listing 5.11 Definition of the Q7 format
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
pub struct Q7(i8);                          #1

Shows a custom Q7 type deriving Copy alongside Clone, comparison, and debugging traits. section 5.5

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

How deep it goes
Contrasts compiling integer and failing struct examples, then shows how deriving Copy changes a custom type’s transfer behavior.
Examples
Uses an i32 function call, a non-Copy Demo struct, and a Q7 fixed-point tuple struct.
What it assumes
Assumes basic Rust functions, variables, structs, and primitive types while introducing ownership differences through concrete examples.
What you can do after
Evaluate/understand whether a Rust value remains accessible after transfer and recognize when deriving Copy enables implicit duplication.
How it connects
Connects Copy semantics with Rust ownership, move semantics, the Copy trait, the Clone trait, and tuple structs.

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.