ownership

Rust Derive Copy for small value types

A struct of Copy fields can implement Copy. Choose this contract deliberately for small value-like data; Copy is part of the public API and can constrain later changes. Deriving Clone as well satisfies the supertrait requirement. Expected output (not executed): 2 6 Why: Both points can be read after assignment because the type implements Copy. Common mistake: Deriving Copy for a type containing a String or implementing Drop.

Formal Syntax & Structure

rust syntaxrust
#[derive(Clone, Copy)]

Working Example

Example Snippetrust
#[derive(Clone, Copy)]struct Point { x: i32, y: i32 }fn main() {    let p = Point { x: 2, y: 6 };    let q = p;    println!("{} {}", p.x, q.y);}
Rust Reference