skip to content

Copy and Clone

Copy types are duplicated implicitly by a bitwise copy, Clone types only when you call clone. Interviewers ask which types can be Copy and why Copy and Drop exclude each other.

on this pageshow

questions

5

In Rust, why can you still use a `Vec2` after `let b = a;`, but not a `Sprite` that holds a `String`?

level: juniorimportance: must knowfreq 80%

answer

  1. implicit versus explicit duplication
  2. a marker trait with no methods
  3. bitwise copy leaves the source valid
  4. String owns a heap buffer

basics

~20 s

A 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
rust
#[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

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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
open as a page

In Rust, which types can implement `Copy`, and why does `#[derive(Clone, Copy)]` fail on a struct with a `String` field?

level: middleimportance: must knowfreq 65%

basics

~20 s

A type can be Copy only if every field is Copy and it has no Drop impl: numbers, bool, char, shared references, raw and function pointers, and tuples or arrays of Copy types. A String field is not Copy, so rustc reports E0204.

open as a page

Why does rustc reject a Rust type that derives `Copy` and also implements `Drop`, reporting error E0184?

level: middleimportance: should knowfreq 50%

basics

~20 s

Copy promises that duplicating a value's bytes duplicates the whole value; Drop says the value owns something that must be released once. Silent copies would each run that release, freeing one resource twice, so rustc forbids the pair with E0184.

open as a page

In Rust, why can calling `.clone()` on a `&T` or a `&str` hand back a reference instead of an owned value, and when is `to_owned` the right call?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Shared references are always Clone, so if T is not Clone, method lookup clones the &T and returns a reference. str cannot be Clone, so clone on a &str gives a &str; to_owned gives the owned form, a String or a Vec.

open as a page

As the lead on a Rust game engine, what code-review rule would you set for `clone()` calls, especially inside the per-frame render loop?

level: principalimportance: should knowfreq 35%

basics

~20 s

Treat clone() on heap-owning types in per-frame code as a review stop: borrow, reuse buffers with clone_from, or make small value types Copy. Outside hot paths, a clone that keeps code simple is fine. Lint the mechanical cases; profile the rest.

open as a page