Code Logo

Derive Clone and Copy

Published at25 Jul 2026
Rust Traits & Generics Easy 0 views
Like0

Write a Rust function that defines a struct Point with x and y fields of type i32, derives the Clone and Copy traits, and demonstrates that copying a Point creates an independent copy. The function takes two integers, creates a Point, creates a copy by assignment, modifies the original, and returns the original's x value to verify it still works.

The #[derive(Clone, Copy)] attribute tells the Rust compiler to automatically generate implementations of the Clone and Copy traits for a struct. Clone provides an explicit .clone() method for duplicating values. Copy is a subtrait of Clone that indicates the type can be duplicated simply by copying bits (memcpy), without needing to call .clone() explicitly.

Copy types are a key part of Rust's ownership model. Primitive types like i32, bool, and f64 implement Copy. User-defined types can implement Copy if all their fields are Copy. After a move, the original Copy value is still usable because the compiler knows it can be cheaply bitwise-copied.

Time complexity is O(1) as Copy types are copied by memcpy. Space complexity is O(1). Derive macros generate efficient implementations at compile time with zero runtime overhead.

Edge cases include structs with all Copy fields (required for derive(Copy)), ensuring Clone is derived before Copy (Copy requires Clone), and understanding that Copy does not work for types with heap-allocated data like String or Vec.

Example Input & Output

Example 1
Input
-1,7
Output
-1
Explanation

Negative original unchanged

Example 2
Input
5,10
Output
5
Explanation

Original stays unchanged after copy

Example 3
Input
42,99
Output
99
Explanation

Copy preserved

Example 4
Input
5,10
Output
10
Explanation

Copy is independent of original

Example 5
Input
42,99
Output
42
Explanation

Original preserved

Algorithm Flow

Recommendation Algorithm Flow for Derive Clone and Copy
Recommendation Algorithm Flow for Derive Clone and Copy

Solution Approach

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

fn solution(a: i32, b: i32) -> i32 {
    let p1 = Point { x: a, y: b };
    let _p2 = p1;
    p1.x
}

Best Answers

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

fn solution(a: i32, b: i32) -> i32 {
    let p1 = Point { x: a, y: b };
    let _p2 = p1;
    p1.x
}