Skip to content
Select theme

When should you clone?

Short answer: clone when the value has to exist in two places at once — a Vec that stores it, or a function you don’t own that takes it by value — and when the copy is small enough that its cost never matters. Everywhere else, borrow first: a & gives the reader what it needs without a second buffer.

A Vec<String> owns its elements. There’s no borrow that lives as long as the vector does, so storing a value you still need means giving the vector a copy of its own:

team: ["Ada", "Grace"]
name is still in hand: Ada

Push name without the clone and the move ends the binding — the vector takes the only copy. The clone is doing real work here: two owners, two buffers, each freed when its own owner goes out of scope. A destructor shows the second buffer. The Gift type from the previous page drops once per owner:

first: teddy bear
second: teddy bear
dropping "teddy bear"
dropping "teddy bear"

Two dropping lines: one per copy, so the text really was duplicated rather than shared. A single buffer would print the line once.

Not every clone is a performance decision. Six bytes of text cost one allocation and one six-byte memcpy:

length: 6 bytes
capacity: 6 bytes
label: v1.2.3
printed: v1.2.3
same buffer: false

The pointers differ, so the clone copied the text instead of sharing it. At this size the allocation is noise next to the println! calls around it, and the borrow that avoids it would need a lifetime threaded through code that runs once at startup. Clone it and move on; if a profile ever disagrees, the fix is one line.

A crate’s function takes String by value and isn’t yours to change. If you still need your copy after the call, the clone at the call site is the price of that boundary:

log: disk almost full
still have: disk almost full

For a function you do own, changing the parameter to &str beats cloning at every call — How to pass ownership of a value to a function covers that move.

Cloning to silence an error you haven’t read is the wrong reason, and in a hot loop it’s a real cost: every iteration allocates. The note: under an E0382 error suggests a borrow first and a clone second, in that order, and the E0382 page lists the fixes. When the value needs many readers rather than two copies, shared ownership is the shape — Rc and Arc belong to the smart pointers chapter.