In Rust, why can you still use a `Vec2` after `let b = a;`, but not a `Sprite` that holds a `String`?
answer
- implicit versus explicit duplication
- a marker trait with no methods
- bitwise copy leaves the source valid
- String owns a heap buffer
basics
~20 sA Vec2 of two f32 fields implements Copy, so let b = a duplicates its bits and a stays valid. A Sprite owns a String, so it is not Copy: the same line moves it, and a duplicate needs an explicit clone().
solid answer
~40 s`Copy` is a marker trait: for a type that implements it, assignment, passing an argument and returning a value duplicate it bit for bit, and the source stays usable. `Vec2 { x: f32, y: f32 }` qualifies because every field is `Copy`, so `#[derive(Clone, Copy)]` compiles. `Sprite` holds a `String`, which owns a heap buffer; a bitwise copy would leave two values responsible for one buffer and free it twice, so `String` is `Clone` but not `Copy`. For a non-`Copy` type, `let s3 = s1;` is a move and `s1` is unusable afterwards. When you really need two independent sprites you write `s1.clone()`, which runs `Clone::clone` and allocates a new buffer for `name`. `Copy` is implicit and cannot be customised; `Clone` is explicit and may run any code.
code
rust · 23 lines#[derive(Debug, Clone, Copy)]
struct Vec2 {
x: f32,
y: f32,
}
#[derive(Debug, Clone)]
struct Sprite {
name: String,
pos: Vec2,
}
fn main() {
let a = Vec2 { x: 1.0, y: 2.0 };
let b = a; // Vec2 is Copy: the bits are duplicated, `a` stays usable
println!("a = {a:?}, b = {b:?}");
let s1 = Sprite { name: String::from("player"), pos: a };
let s2 = s1.clone(); // explicit: a new heap buffer for `name`
let s3 = s1; // no Copy: this is a move, `s1` is unusable from here on
println!("{} at {:?}, {} at {:?}", s2.name, s2.pos, s3.name, s3.pos);
println!("same heap buffer: {}", s2.name.as_ptr() == s3.name.as_ptr());
}go deeper
Recall the two behaviours: Copy types duplicate silently on assignment and the source stays usable; every other type moves, and a deliberate duplicate needs a clone() call.
Explain why: Copy is a bitwise duplicate with no method to override, so only types whose bytes are the whole value qualify, and a String's heap buffer rules it out.
Show that you read every clone() as a possible allocation, and that a copy and a move can compile to the same byte copy, so the real cost gap is Clone on heap-owning types.
Frame it as API design: deriving Copy on a small value type removes clone noise at every call site but commits the type to staying plain data for good.
## Two ways to duplicate a value Rust has two standard traits for making a second value out of a first one, and they differ in **who decides** and **what it costs**. - **`Copy`** (in `std::marker`) is a marker trait with no methods. When a type implements it, the compiler duplicates values of that type **implicitly** wherever it would otherwise move them: on `let b = a;`, when passing `a` to a function, when returning it, when capturing it by value. - **`Clone`** (in `std::clone`) has a method, `clone(&self) -> Self`. Nothing happens unless you **call it explicitly**, and its implementation may run arbitrary code, including heap allocation. Every `Copy` type must also implement `Clone`, because `Clone` is a supertrait of `Copy` (`pub trait Copy: Clone`). The reverse is not true: plenty of types are `Clone` but not `Copy`. ## Copy: implicit and bitwise The standard library's own documentation says the behaviour of `Copy` "is not overloadable; it is always a simple bit-wise copy". That is why only types whose bytes *are* the whole value qualify. A 2D game's position type is the textbook case: ```rust #[derive(Debug, Clone, Copy)] struct Vec2 { x: f32, y: f32 } let a = Vec2 { x: 1.0, y: 2.0 }; let b = a; // a copy: `a` is still valid println!("{a:?}"); // compiles ``` Without `Copy`, the same `let b = a;` would be a **move**: ownership passes to `b` and the compiler rejects any later use of `a` with E0382. With `Copy`, the source keeps its value and both bindings are independent. A useful fact for interviews: under the hood, a copy and a move can both compile to the same copy of bytes, and the optimiser often removes either. The difference is **what the compiler lets you do with the source afterwards**, not the machine code. ## Clone: explicit and possibly expensive `Clone` is for types that need real work to duplicate. The standard library's example is `String`: its `Clone` implementation "needs to copy the pointed-to string buffer in the heap". A `#[derive(Clone)]` on a struct generates a `clone` that calls `clone` on each field, so for a sprite: ```rust #[derive(Debug, Clone)] struct Sprite { name: String, pos: Vec2 } let s2 = s1.clone(); // allocates a new buffer for `name`, copies `pos` let s3 = s1; // a move: `s1` is unusable from here on ``` After the clone, `s2.name` and `s3.name` live in different heap buffers; changing one never affects the other. ## Why String cannot be Copy A `String` is a pointer, a length and a capacity, plus the duty to free its buffer when it is dropped. If assignment copied those three words implicitly, two `String` values would point at one buffer and both would free it: a **double free**. Rust prevents that by giving `String` move semantics plus an explicit `Clone`. The same reasoning rules out `Vec<T>`, `Box<T>` and any struct that contains them, such as `Sprite`. | | `Vec2` | `Sprite` | |---|---|---| | Fields | two `f32` | a `String` and a `Vec2` | | Traits | `Clone + Copy` | `Clone` only | | `let b = a;` | copy, `a` stays usable | move, `a` is unusable | | Second value | implicit, no call | `a.clone()`, allocates | ## Where implicit copies show up A `Copy` field changes more than plain assignments. Because reading a `Copy` value copies it, these all compile and leave the source intact: - `let p = sprite.pos;` copies the `Vec2` out of a `Sprite` without moving the sprite. - `let q = sprites[0].pos;` copies a position out of a `Vec<Sprite>` by index. - Passing `a` to `fn length(v: Vec2) -> f32` copies it, so `a` is still usable after the call. The same reads on the `String` field are different: `let n = sprites[0].name;` fails with E0507, "cannot move out of index of `Vec<Sprite>`", because a non-`Copy` value cannot be moved out of a collection by indexing. There you borrow (`&sprites[0].name`) or clone. ## What a strong answer covers 1. Name the mechanism: `Copy` changes assignment from a move into a duplicate; `Clone` is a method you call. 2. Explain the eligibility rule: a bitwise duplicate must be a complete, safe duplicate, so types that own heap memory are excluded. 3. Mention cost: a `Copy` is cheap by construction, while `clone()` on a heap-owning type allocates and copies data. 4. Note that calling `.clone()` on a `Copy` type compiles and just returns a copy, but is redundant; Clippy's default `clone_on_copy` lint flags it. Interviewers often follow up by asking you to fix code that fails with "borrow of moved value". The right fix depends on intent: borrow the value if you only need to read it, move it if the old binding is finished, and clone only when you genuinely need two owners of independent data.
- Is a copy faster than a move in Rust?Not inherently. Both a copy and a move can compile to the same copy of the value's bytes, and the optimiser often removes either. What differs is whether the source stays usable. The cost that really differs is `Clone` on a heap-owning type, which allocates and copies the pointed-to data.
- Can you call `clone()` on a `Copy` type such as `Vec2`?Yes. `Copy` requires `Clone`, so `a.clone()` compiles and returns a copy. On a concrete `Copy` type it is redundant, and Clippy's default `clone_on_copy` lint warns about it. The `Clone` impl exists so that generic code bounded by `T: Clone` also accepts `Copy` types.
- Does `let s2 = s1.clone();` on a derived-`Clone` `Sprite` share the name buffer with `s1`?No. The derived `clone` calls `clone` on each field, and `String`'s `clone` allocates a new buffer and copies the bytes, so the two sprites are independent. A field shares data after cloning only when its own `Clone` shares, such as a reference-counted pointer.
- Copy and Clone are the same trait under two names
- let b = a always moves, so a is never usable afterwards
- Any struct becomes Copy if you add derive(Copy)
- Implementing Copy lets you customise how the bytes are duplicated
- Cloning a String only copies its pointer, so it is cheap