Copy trait
- Rust course
- Beginner
- Lesson 44/115
- 4 min
Learn how Copy types are duplicated instead of moved.
The Copy trait
Small types that live entirely on the stack implement the Copy trait and are copied, not moved, on assignment: all integers, floats, bool, char, and tuples and arrays made only of Copy types.
let x = 5;
let y = x; // a copy; x is still valid
println!("{x} {y}");
let p = (1, 2.5);
let q = p; // the tuple is Copy too
println!("{:?}", p);String, Vec and Box aren't Copy because they own heap memory.
Copy for your own type
You can add #[derive(Clone, Copy)] to your own struct if it has only Copy fields. Copy always requires Clone as well:
#[derive(Debug, Clone, Copy)]
struct Nokta {
x: i32,
y: i32,
}
let a = Nokta { x: 1, y: 2 };
let b = a; // copied
println!("{:?} {:?}", a, b);Practice Copied point
Define #[derive(Debug, Clone, Copy)] struct Nokta { x: i32, y: i32 }. Do let a = Nokta { x: 1, y: 2 };, let mut b = a;, b.x = 10; and print a and b with {:?} {:?}.
Starter code
fn main() {
// buraya yaz
}Sample solution
#[derive(Debug, Clone, Copy)]
struct Nokta {
x: i32,
y: i32,
}
fn main() {
let a = Nokta { x: 1, y: 2 };
let mut b = a;
b.x = 10;
println!("{:?} {:?}", a, b);
}Expected output
Nokta { x: 1, y: 2 } Nokta { x: 10, y: 2 }
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which isn't <code>Copy</code>?
- char
- (i32, String) Correct answer
- (i32, f64)
- [u8; 4]
Explanation: A tuple is Copy only if all its elements are Copy; because it contains a String, this tuple is moved.
2 Copyable type
#[derive(Clone, ____)]
struct Renk(u8, u8, u8);
#[derive(Clone, Copy)]
struct Renk(u8, u8, u8);
Explanation: Deriving Copy makes the value copy automatically on assignment.
3 Type and behavior
| Term | Meaning |
|---|---|
i32 |
Copy: copied on the stack |
String |
Move: heap ownership moves |
(i32, String) |
Move: one field is not Copy |
#[derive(Clone, Copy)] |
Makes your own type Copy |