Course contentsShow
← Rust
Lesson 34 of 1,9101. Rust Fundamentals and ToolingFree lesson

The Copy Trait Implementation

Define custom types that behave like primitives by opting into the Copy trait.

In this lesson, you will learn how to make your custom data types behave exactly like primitive integers or booleans by implementing the Copy trait.

Understanding the Default Behavior

By default, when you assign a variable to another in Rust, the value is "moved." If you have a custom struct, Rust assumes that moving it is safer than copying it, especially if the data is large or holds resources (like a Box).

However, sometimes you create small, simple structures—like a Point with two i32 coordinates—that are very cheap to duplicate. If you want these types to be copied automatically instead of moved, you can opt into the Copy trait.

How to Implement Copy

To implement Copy, your type must also implement the Clone trait. The Clone trait defines how to make an explicit copy (using the .clone() method), while the Copy trait tells Rust to perform that copy automatically whenever the variable is moved.

Here is how you define a simple type that behaves like a primitive:

#[derive(Debug, 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: {:?}, p2: {:?}", p1, p2);
}

Why use #[derive(...)]?

In this example, we used #[derive(Clone, Copy)]. This is a built-in Rust feature that tells the compiler to automatically write the necessary code to duplicate your struct field by field.

Important: You can only implement Copy if all of the fields inside your struct also implement Copy. If you tried to add a String or a Box to the Point struct above, the compiler would stop you. Those types manage heap memory, and Copy is reserved for types that live entirely on the stack and can be duplicated by a simple "bitwise" copy.

By opting into Copy, you allow your custom types to act like integers, making your code cleaner and more ergonomic to write.

Key Takeaway: Implementing the Copy trait enables a type to be duplicated automatically on assignment instead of being moved, provided all its internal fields are also Copy compatible.