Module 2 · Ownership & memory
2.3Copy vs. Clone
Which Rust types copy themselves on assignment, which need an explicit .clone(), what each one costs, and how they compare with the copies you already make.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
b = a with a number | Copies the number | Copies the value (value type) | Copies the value: i32 is Copy |
b = a with a small record | Shares one object | struct: copies it. class: shares one object | Moves it, unless the type derives Copy |
| Copying an object on purpose | { ...obj } (shallow) or structuredClone(obj) (deep) | with on records (shallow), ICloneable, or a copy constructor | .clone(): copies everything the value owns |
| Making your own type copyable | Nothing to opt into | Declare it as a struct | #[derive(Clone)], plus Copy if every field is Copy |
| Seeing the cost in the code | No; a deep copy and a shallow one look alike at the call site | No; a large struct copy looks like any assignment | Yes: assignment never copies heap data; that takes a visible .clone() |
In the last lesson, assigning a Vec moved it, while assigning an i32 left both variables usable. That difference has a name. Types that implement the Copy trait are copied on every assignment, like numbers in TypeScriptC# value types. Every other type moves, and if you want a second, independent value, you ask for one with .clone(). This lesson shows which types are which, what each copy costs, and how to choose.
Some types copy, the rest move
Here’s a small Point copied and then changed. TypeScript needs an explicit spread, because objects are shared by default.C# copies because Point is a struct. Rust copies because Point derives Copy.
type Point = { x: number; y: number };
const start: Point = { x: 1, y: 2 };
const end = { ...start }; // without the spread, both names would share one object
end.x = 10;
console.log(`${start.x} ${end.x}`);var start = new Point { X = 1, Y = 2 };
var end = start; // a struct: assignment copies it
end.X = 10;
Console.WriteLine($"{start.X} {end.X}");
struct Point
{
public int X;
public int Y;
}#[derive(Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
let start = Point { x: 1, y: 2 };
let mut end = start; // Point is Copy: `start` stays usable
end.x = 10;
println!("{} {}", start.x, end.x);Output
1 10
#[derive(Clone, Copy)] asks the compiler to implement both traits for Point. Copy needs Clone too, which is why you always see them together. Remove that line and let mut end = start; becomes a move, so reading start.x afterwards fails:
struct Point {
x: i32,
y: i32,
}
let start = Point { x: 1, y: 2 };
let mut end = start;
end.x = 10;
println!("{} {}", start.x, end.x);Rust doesn't compile this: error E0382
error[E0382]: borrow of moved value: `start`
--> main.rs:9:19
|
6 | let start = Point { x: 1, y: 2 };
| ----- move occurs because `start` has type `Point`, which does not implement the `Copy` trait
7 | let mut end = start;
| ----- value moved here
8 | end.x = 10;
9 | println!("{} {}", start.x, end.x);
| ^^^^^^^ value borrowed here after move
|
note: if `Point` implemented `Clone`, you could clone the value
--> main.rs:1:1
|
1 | struct Point {
| ^^^^^^^^^^^^ consider implementing `Clone` for this type
...
7 | let mut end = start;
| ----- you could clone this value
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)Mental model shiftCopy or move is a property of the type
In TypeScript, assigning an object always shares it, and a copy is something you make by hand.In C#, the type’s author decides between struct (copied) and class (shared). In Rust, every type is a value, and the author decides between Copy (copied) and not Copy (moved). Nothing is ever shared by plain assignment. Sharing is something you ask for, with a borrow (Module 3) or Rc<T> (Module 11).
Which types are Copy
A type can be Copy only if copying its bytes gives a complete, independent value. That’s true for:
- integers, floats,
boolandchar - shared references (
&T): copying a reference gives a second reference to the same data (but not&mut T, which must stay unique) - tuples and arrays whose elements are all
Copy, such as(i32, f64)or[u8; 4] - your own structs and enums, if every field is
Copyand you derive it
It’s never true for a type that owns heap memory, like String, Vec<T> or Box<T>, or for a type that runs cleanup code when it’s dropped. You’ll see why under the hood.
Clone: an explicit, deep copy
For everything else there’s .clone(). It’s an ordinary method from the Clone trait, and for the standard collections it copies everything they own: the vector’s buffer and every element in it. (Shared-ownership pointers such as Rc<T> are the exception: cloning one adds an owner to the same value instead of copying it. Module 11 covers them.)
const rounds = [[90, 85], [70]];
const copy = structuredClone(rounds); // deep: the inner arrays are copied too
copy[0]?.push(100);
console.log(`${rounds[0]?.length} ${copy[0]?.length}`);var rounds = new List<List<int>> { new() { 90, 85 }, new() { 70 } };
var copy = rounds.Select(round => new List<int>(round)).ToList(); // deep copy by hand
copy[0].Add(100);
Console.WriteLine($"{rounds[0].Count} {copy[0].Count}");let rounds = vec![vec![90, 85], vec![70]];
let mut copy = rounds.clone(); // clones the outer Vec and both inner ones
copy[0].push(100);
println!("{} {}", rounds[0].len(), copy[0].len());Output
2 3
TypeScript makes you pick between a shallow copy ([...rounds]) and a deep one (structuredClone).C# makes you pick between a shallow copy (new List<List<int>>(rounds)) and a deep one you build by hand. In Rust, Vec<Vec<i32>> can’t share its inner vectors between two owners, so .clone() has to copy them. There’s no shallow version to pick by mistake.
That also means .clone() can be expensive. Cloning a Vec<String> of 1,000 names allocates a new buffer and then 1,000 new strings. The cost is right there in the code, as a method call you can search for.
Idiomatic RustA clone you can see is a cost you can see
Rust never runs a clone you didn’t write. let b = a; only copies the value’s inline bytes, whatever the type: it never allocates and never runs your code. If a line duplicates heap data, it says .clone().
Your own types
Most structs that hold a String or a Vec can be Clone but not Copy. Deriving Clone gives the struct a .clone() that clones each field in turn.
Here’s the Rust version of a TypeScript spread like { ...user, age: 37 }a C# with expression: copy a user and change one field.
type User = { name: string; age: number };
const user: User = { name: "Ada", age: 36 };
const older = { ...user, age: 37 };
console.log(`${user.name} ${user.age} -> ${older.name} ${older.age}`);var user = new User("Ada", 36);
var older = user with { Age = 37 };
Console.WriteLine($"{user.Name} {user.Age} -> {older.Name} {older.Age}");
record User(string Name, int Age);#[derive(Clone)]
struct User {
name: String,
age: u32,
}
let user = User {
name: String::from("Ada"),
age: 36,
};
let older = User {
age: 37,
..user.clone()
};
println!("{} {} -> {} {}", user.name, user.age, older.name, older.age);Output
Ada 36 -> Ada 37
..user.clone() fills in the remaining fields from a clone of user. Without .clone(), ..user would move name out of user, and the last line couldn’t print user.name. Struct update syntax is covered in Structs and impl blocks.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
| Copy | The type is small, fixed-size and owns no heap data: numbers, bool, char, &T, small structs of those. | Copying a few bytes costs the same as moving them, and both variables stay usable. | Built-in types: just assign. Your own: #[derive(Clone, Copy)]. |
| Move | The receiver should own the value from now on, and you’re done with it. | Cheap: no heap data is copied, and the compiler stops you using the old name. | let b = a; or keep(a) for any non-Copy type. |
Borrow (&) | The receiver only needs to read the value for a while. | No copy at all, and you keep ownership. | Pass &a. See References. |
| Clone | You need two independent values that can change separately. | Each owner frees its own copy, so nothing is shared. | let b = a.clone(); with #[derive(Clone)] on your types. It copies all owned heap data, so it costs time and memory. |
Rule of thumb: derive Copy for small value-like types with no heap data, such as a point, an ID or a color. For everything else, borrow when you only read, move when you’re done, and clone only when you really need two copies. A .clone() added just to quiet the compiler usually means a borrow was the better fix.
The same choice as questions to ask in order:
Is the type
Copy(numbers,bool,char,&T, or a small struct that derivesCopy)?YesNoJust assign:
let b = a;copies itBoth variables stay usable. Copying a few bytes costs the same as moving them.Does the receiver only need to read the value for a while?
YesNoBorrow: pass
&aNo copy at all, and you keep ownership.Are you done with the value, so the receiver can own it from now on?
YesNoMove:
let b = a;orkeep(a)No heap data is copied, and the compiler stops you using the old name.Otherwise: Clone:
let b = a.clone();gives two independent values, at the cost of copying all the heap data
Under the hood
Copy and a move do the same thing at runtime: they copy the value’s inline bytes (for a String, the pointer, length and capacity). The only difference is what the compiler lets you do next. After a copy, both variables are usable. After a move, only the new one is.
Clone is a real method call. For a String, it allocates a new heap buffer and copies the text into it:
let name = String::from("Ada");
let copy = name.clone();
println!("{name} {copy}");Now picture String as Copy. A bitwise copy would duplicate only the pointer, length and capacity, so both variables would point at the same buffer, and both would free it at the end of the scope: a double free. That’s why the compiler refuses Copy on any type with a field that isn’t Copy:
#[derive(Clone, Copy)]
struct User {
name: String,
age: u32,
}Rust doesn't compile this: error E0204
error[E0204]: the trait `Copy` cannot be implemented for this type
--> main.rs:1:17
|
1 | #[derive(Clone, Copy)]
| ^^^^
2 | struct User {
3 | name: String,
| ------------ this field does not implement `Copy`The same goes for types that implement Drop (custom cleanup, Module 11): if copying were implicit, the cleanup would run once per copy.
Common pitfalls
Common pitfallYour everyday copies are shallow
TypeScript’s spread copies only the top level. Nested objects are still shared:
const user = { name: "Ada", tags: ["math"] };
const copy = { ...user };
copy.tags.push("poetry");
console.log(user.tags.length); // 2: both share one tags arrayC#‘s everyday copy tools copy only the top level, so nested objects are still shared. user with { Age = 37 } copies the reference to a List<string> field, not the list, and new List<List<int>>(rounds) copies the references to the inner lists, not the lists.
Rust’s derived .clone() clones every field, so a cloned User with a tags: Vec<String> field gets its own vector and its own strings.
Common pitfallTaking a Copy value out makes a copy
Reading a Copy element into a variable copies it, so changing the variable doesn’t change the collection, just as with a number read out of a TypeScript array, as you know from a C# List<Point>. In Rust you can change the element in place instead:
#[derive(Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
let mut points = [Point { x: 0, y: 0 }];
let mut first = points[0]; // a copy
first.x = 5; // changes the copy only
points[0].x = 7; // changes the element in the array
println!("{} {}", first.x, points[0].x);This prints 5 7. In C#, points[0].X = 7 on a List<Point> doesn’t compile (CS1612), because the indexer returns a copy. Rust’s indexing gives you the element itself, in arrays and in Vec alike.
Common pitfallDon't derive Copy on large types
Copy makes copies silent. That’s fine for a few bytes, but a struct holding a [u8; 4096] buffer would be copied in full on every assignment and function call. Derive Clone only, so each copy has to be a visible .clone(). The same advice applies to large C# structs.
Try it yourself
Exercise: port this to Rust
Port this program to Rust. Make Point a Copy type so origin stays usable, and make backup an independent copy of path.
type Point = { x: number; y: number };
const origin: Point = { x: 0, y: 0 };
const moved = { ...origin, x: 5 };
const path = [origin, moved];
const backup = structuredClone(path);
path.push({ x: 9, y: 9 });
console.log(`${backup.length} ${path.length} ${origin.x}`);var origin = new Point(0, 0);
var moved = origin with { X = 5 };
var path = new List<Point> { origin, moved };
var backup = new List<Point>(path);
path.Add(new Point(9, 9));
Console.WriteLine($"{backup.Count} {path.Count} {origin.X}");
record struct Point(int X, int Y);Expected output
2 3 0
Show a hint
Derive Clone and Copy on Point, so origin stays usable after it goes into the vector and into the struct update. Then clone the vector to make the backup before you push.
Show a solution
#[derive(Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let origin = Point { x: 0, y: 0 };
let moved = Point { x: 5, ..origin };
let mut path = vec![origin, moved];
let backup = path.clone();
path.push(Point { x: 9, y: 9 });
println!("{} {} {}", backup.len(), path.len(), origin.x);
}Point holds two i32s, so it can be Copy: building moved with ..origin and putting origin in the vector both copy it. Vec<Point> owns a heap buffer, so it can't be Copy, and backup needs an explicit clone. Because Point has no heap data, that clone is cheap: one allocation and a copy of the bytes.
Saved in this browser only.