What is the difference between Copy and Clone traits in Rust?
I just started learning Rust and got confused about two traits — Copy and Clone. They both seem to allow copying values, but the compiler behaves differently.
Here's an example that confused me. I'm trying to copy a struct:
```rust
struct Point {
x: i32,
y: i32,
}
fn main() {
let p1 = Point { x: 10, y: 20 };
let p2 = p1; // move
let p3 = p1; // error: use of moved value
}
```
If I add `#[derive(Copy)]`, the code works:
```rust
#[derive(Copy, Clone)]
struct Point {
x: i32,
y: i32,
}
```
But if I only use `Clone`, I have to explicitly call `.clone()`:
```rust
let p2 = p1.clone();
```
Why is that? When should I use Copy and when Clone? What is the fundamental difference? And why does Copy require Clone (I've seen that
No answers yet.
Log in to leave an answer
Blogs