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
