Derive Clone and Copy
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
Negative original unchanged
Original stays unchanged after copy
Copy preserved
Copy is independent of original
Original preserved
Algorithm Flow

Solution Approach
Best Answers
#[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
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
