Course contentsShow
← Rust
Lesson 97 of 1,9102. The Ownership ModelFree lesson

Primitive Types and Traits

Leverage built-in traits to explicitly opt-in to copy behavior for custom types.

Opting-in to Copy Semantics

In this lesson, you will learn how to make your custom types behave like primitive integers by leveraging the Copy trait to explicitly enable bitwise copying.

The Default: Move Semantics

So far, we have seen that when you assign a variable to another in Rust, the default behavior is a move. The ownership of the data is transferred, and the original variable is no longer accessible. For complex types, this prevents double-free errors. However, for small, simple data structures—like a point on a grid or a color value—this strict ownership transfer can feel cumbersome.

Explicitly Opting In with Copy

Primitive types like i32 or bool are special because they are stored entirely on the stack and have a fixed size. Rust marks these types with the Copy trait. When you assign an i32, Rust simply copies the bytes from the source to the destination, and both variables remain valid.

You can grant your own custom types this same "primitive-like" behavior by deriving the Copy trait. When a type implements Copy, the compiler treats it as a simple block of memory that can be duplicated safely.

Consider this custom Point struct:

#[derive(Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p1 = Point { x: 10, y: 20 };
    let p2 = p1; // Because of Copy, p1 is still usable here!
    
    println!("p1 is still valid: {}, {}", p1.x, p1.y);
}

Why Opt-in?

By deriving Copy, you are explicitly telling the compiler: "This data is small and cheap to duplicate; there are no hidden resources like heap allocations to manage." It is important to note that you cannot implement Copy on a type that manages heap-allocated memory (like a String or a Vec), as that would violate the ownership model and lead to memory unsafety. By choosing to opt-in, you keep your code clean while maintaining Rust’s strict safety guarantees.

Key Takeaway: By deriving Copy on a simple, stack-only struct, you enable implicit bitwise copying, allowing you to use the type without triggering move semantics.