Sub topic 12
clone_from and reusing existing allocations
This chapter assumes you know how Clone and Copy differ, how #[derive(Clone)] works, and that String and Vec own heap memory. The previous chapters showed .clone() creating a new value. This chapter covers clone_from, a second method on the Clone trait that overwrites an existing value and can reuse the memory that value already owns.
The method and its default
Clone has two methods. clone is required. clone_from has a default body:
pub trait Clone: Sized {
fn clone(&self) -> Self;
fn clone_from(&mut self, source: &Self) {
*self = source.clone()
}
}The default does the obvious thing. It builds a fresh value with clone, drops the old contents of self, and moves the new value in. That costs one allocation for the new value and one deallocation for the old one, so the default saves nothing.
A type can override clone_from to do better. It already holds a buffer, so it can copy the source's data into that buffer and skip the allocator. The result must still equal *self = source.clone(). Only the cost differs.
Seeing the reuse
The spine example for this chapter shows the basic call:
fn main() {
let source = String::from("a longer piece of text");
let mut target = String::with_capacity(64);
target.clone_from(&source);
println!("{target}");
}The output is a longer piece of text. The target string was created with room for 64 bytes. String::clone_from copies the 22 bytes into that buffer and leaves the capacity alone. Nothing is allocated.
The next program makes this visible by comparing buffer addresses. It also checks the other way of doing it, assignment from clone().
fn main() {
let source = String::from("a longer piece of text");
let mut a = String::with_capacity(64);
let before = a.as_ptr();
a.clone_from(&source);
println!("clone_from kept buffer: {}", a.as_ptr() == before);
println!("capacity still >= 64: {}", a.capacity() >= 64);
let mut b = String::with_capacity(64);
let before = b.as_ptr();
b = source.clone();
println!("assignment kept buffer: {}", b.as_ptr() == before);
}It prints:
clone_from kept buffer: true
capacity still >= 64: true
assignment kept buffer: falseThe assignment form must be false. The right-hand side source.clone() is evaluated while the old buffer is still alive, so the new buffer cannot have the same address.
What the standard library overrides
The standard library overrides clone_from on the types where it pays off most.
Stringforwards to its innerVec<u8>. It clears the contents and copies the bytes in. It reallocates only if the source is longer than the current capacity.Vec<T>truncates the target to the source's length. It callsclone_fromon each element position that exists in both, then clones and appends any extra elements.Box<T>forwards toT::clone_from, so the heap slot is reused and the inner value gets its own chance to reuse memory.
The Vec<T> case is worth noting. For Vec<String>, the reuse goes one level deeper. Each String already in the target keeps its buffer, and only the elements beyond the old length are newly allocated. Which other standard types override clone_from has varied between Rust versions, so check the documentation for the type you care about.
Types such as Rc<T> and Arc<T> use the default. Their clone is already cheap, because it increments a counter, so there is nothing to reuse.
A loop that benefits
The usual place for clone_from is a loop that refreshes a long-lived buffer on every iteration.
fn main() {
let states = vec![
vec![String::from("alpha"), String::from("beta"), String::from("gamma")],
vec![String::from("delta"), String::from("epsilon")],
vec![String::from("zeta"), String::from("eta"), String::from("theta")],
];
let mut snapshot: Vec<String> = Vec::new();
for state in &states {
snapshot.clone_from(state);
println!("{} items: {:?}", snapshot.len(), snapshot);
}
}Its output is:
3 items: ["alpha", "beta", "gamma"]
2 items: ["delta", "epsilon"]
3 items: ["zeta", "eta", "theta"]The first pass allocates, because snapshot starts empty. On later passes the outer Vec already has enough capacity, and the element strings that still exist are overwritten in place. The buffer works as a scratch area that stabilises at the size of the largest state. Writing snapshot = state.clone() would instead allocate and free a new outer Vec and every inner String on each iteration.
The same pattern appears in:
- the previous-frame buffer in a game or simulation loop
- backtracking searches that copy a partial solution at each step
- undo stacks that store snapshots
- any cache that is refreshed from a master copy
Derive does not give you this
#[derive(Clone)] generates only clone. It does not generate clone_from, so a derived struct falls back to the default body, even when every field is a String or Vec with a good clone_from of its own. Calling clone_from on a derived struct is correct, but it saves nothing.
To get the savings you must write clone_from by hand and forward to each field. The chapter on manual Clone showed a Counter type. Here is a larger type with several owned buffers:
#[derive(Debug)]
struct Record {
id: u32,
name: String,
tags: Vec<String>,
}
impl Clone for Record {
fn clone(&self) -> Self {
Record {
id: self.id,
name: self.name.clone(),
tags: self.tags.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.id = source.id;
self.name.clone_from(&source.name);
self.tags.clone_from(&source.tags);
}
}
fn main() {
let source = Record {
id: 7,
name: String::from("Ada Lovelace"),
tags: vec![String::from("math"), String::from("engines")],
};
let mut target = Record {
id: 1,
name: String::with_capacity(32),
tags: Vec::with_capacity(8),
};
target.name.push_str("old");
target.tags.push(String::from("stale"));
let name_ptr = target.name.as_ptr();
let tags_ptr = target.tags.as_ptr();
target.clone_from(&source);
println!("{target:?}");
println!("name buffer reused: {}", target.name.as_ptr() == name_ptr);
println!("tags buffer reused: {}", target.tags.as_ptr() == tags_ptr);
}The output is:
Record { id: 7, name: "Ada Lovelace", tags: ["math", "engines"] }
name buffer reused: true
tags buffer reused: trueThe first tag, "stale", was overwritten in place by "math". The second tag, "engines", was appended to the existing vector. The target's capacities of 32 bytes and 8 elements were large enough, so nothing was reallocated.
Rules for writing your own clone_from
- Keep it equivalent to the default. After
a.clone_from(&b),amust be indistinguishable fromb.clone(). Forward every field, including the cheap ones. A forgotten field is a silent bug, and the compiler cannot catch it becauseclone_fromtakes&mut selfand never constructs the struct. - Forward, don't reimplement. Call
field.clone_from(&source.field)so each field type picks its own best strategy. Do not hand-writeclearandextendunless the field type needs it. - Expect partial updates on panic. If a field's
clonepanics halfway through,selfis left with some fields updated and others not. It must still be safe to drop and safe to use, but its value is unspecified. Safe field-by-field code gives you this automatically. - Do not worry about aliasing.
&mut selfand&Selfcannot refer to the same value, so you never need to handlex.clone_from(&x).
A related method: clone_into
Borrowed types such as str and [T] cannot implement Clone themselves, because they are unsized. They get the same optimisation through ToOwned::clone_into, which writes into an existing owned value:
fn main() {
let mut buf = String::with_capacity(32);
for word in ["one", "two", "three"] {
word.clone_into(&mut buf);
println!("{buf}");
}
}The output is one, two, three on separate lines, all from one buffer. The default clone_into does *target = self.to_owned(). str overrides it to reuse the String's allocation.
When it is worth it, and when not
Use clone_from when the target is long-lived, the clone happens repeatedly, and the type owns heap memory. Skip it in these cases:
Copytypes and small values.a = bis already a plain memory copy. Callingclone_fromon ani32adds nothing.- One-off clones. There is no previous allocation to reuse.
RcandArc. A reference-count increment has no allocation to save.- Derived types. Without a manual override,
clone_frombehaves exactly like assignment.
The saving also depends on how often the capacities fit. Measure with a benchmark or an allocation counter before you add manual clone_from code to a type. The extra method is more code to keep in sync with the struct's fields.
Clippy and clone_from
Clippy has a lint called assigning_clones. It flags code like target = source.clone() and suggests target.clone_from(&source). It sits in an opt-in lint group in current versions, so enable it deliberately if you want it and check your Clippy version's documentation for the group. Treat the lint as a prompt to look, not as a command. On a type with the default clone_from, following the suggestion changes nothing. It helps only when the type's clone_from is overridden.
Exercise
A struct Config has #[derive(Clone)] and contains a String and a Vec<String>. Inside a hot loop you write current.clone_from(&template). Does this avoid allocations when current already has enough capacity? What do you change so that it does?
Show answer
No. #[derive(Clone)] generates only clone, so clone_from uses the default body *self = source.clone(), which allocates a new value and drops the old one. To get the reuse, remove the derive and implement Clone by hand. Keep clone as is, and add a clone_from that calls self.field.clone_from(&source.field) for every field. Then the String and Vec<String> fields reuse their own buffers.
Exercise
You run let mut v: Vec<String> = vec![String::from("a"), String::from("b"), String::from("c")]; and then v.clone_from(&vec![String::from("x")]);. What is v afterwards, and which of the original elements' allocations is reused?
Show answer
v is ["x"]. Vec::clone_from truncates the target to the source length, which drops the strings "b" and "c". It then calls clone_from on the first element, so the string that held "a" is overwritten with "x" and keeps its buffer. No new element needs to be appended.