Sub topic 3
Clone: duplicating explicitly with .clone()
This chapter covers the Clone trait: what it promises, how .clone() behaves for different types, and where it goes wrong. It assumes you know basic Rust syntax (structs, enums, functions, traits), ownership and borrowing basics, and how to read compiler error messages. The previous chapter showed that Copy types duplicate implicitly. Here we look at the explicit alternative.
What Clone is
Clone is a trait in the standard library. A type that implements it can produce a new, independent value from a shared reference to an existing one. The trait is defined like this:
pub trait Clone: Sized {
fn clone(&self) -> Self;
fn clone_from(&mut self, source: &Self) {
*self = source.clone();
}
}Three details matter here.
clonetakes&self. The original is only borrowed, so it stays usable afterwards. Nothing is moved.clonereturnsSelf. The result is a new value that you own.- The call is explicit. The compiler never inserts a
.clone()for you. When a value is duplicated this way, the wordcloneappears in the source.
The last point is the main design difference from Copy. A Copy duplication happens silently on every assignment or function call. A Clone duplication happens only where you write it, which makes the cost visible in code review.
clone_from has a default body, so you rarely write it yourself. A later chapter covers why it exists.
Cloning after a move error
The most common reason to reach for .clone() is a "use of moved value" error. A String is not Copy, so assigning it moves it. Cloning gives the second binding its own copy instead:
fn main() {
let s = String::from("hi");
let t = s.clone();
println!("{s} {t}");
}Both s and t are valid at the end. Each owns its own heap buffer. If you change one, the other is unaffected:
fn main() {
let original = String::from("hi");
let mut copy = original.clone();
copy.push_str(" there");
println!("{original}");
println!("{copy}");
}This prints hi and then hi there.
What a clone does for common types
"Clone" does not mean one fixed operation. Each type decides what duplicating it means. The table lists the most common cases.
| Type | What `.clone()` does | Relative cost |
|---|---|---|
| `i32`, `bool`, `char` | Copies the bits | Trivial |
| `String` | Allocates a new buffer and copies the bytes | Proportional to length |
| `Vec<T>` | Allocates a new buffer and clones every element | Proportional to length, plus the cost of each element's clone |
| `Box<T>` | Allocates a new box and clones the contents | Cost of cloning `T`, plus one allocation |
| `Option<T>` | Clones the inner value if present | Cost of cloning `T` |
| `Rc<T>`, `Arc<T>` | Copies the pointer and increments a reference count | Constant, no deep copy |
| `&T` | Copies the reference | Trivial |
Every Copy type is also Clone, and its clone is just a bitwise copy. The interesting cases are the types that own heap memory.
Deep copies: String and Vec
Cloning a Vec<String> is a deep copy. The vector allocates a new buffer, and then each String inside allocates its own buffer too. For a vector of 1,000 strings, that is 1,001 allocations.
fn main() {
let names = vec![String::from("Ada"), String::from("Grace")];
let mut copy = names.clone();
copy[0].push_str(" Lovelace");
println!("{:?}", names);
println!("{:?}", copy);
}The output is:
["Ada", "Grace"]
["Ada Lovelace", "Grace"]The two vectors share nothing, so changing one cannot affect the other. That independence is the point of Clone, and it is also where the cost comes from.
Shallow clones: Rc and Arc
Rc<T> and Arc<T> are reference-counted pointers. Their clone does not touch the data they point to. It copies the pointer and adds one to a counter:
use std::rc::Rc;
fn main() {
let a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
println!("{}", Rc::strong_count(&a));
println!("{}", Rc::ptr_eq(&a, &b));
}This prints 2 and then true. Both a and b point to the same vector. The cost is constant no matter how large the vector is.
Writing Rc::clone(&a) instead of a.clone() is a common convention. It tells the reader that this is a cheap pointer copy and not a deep copy. Both forms do the same thing.
The next diagram contrasts the two behaviors.
Clone requires Clone all the way down
A type can be cloned only if its contents can be. If you derive Clone, every field must implement Clone. A struct holding a type that is not Clone cannot derive it:
use std::fs::File;
// #[derive(Clone)] // error: the trait bound `File: Clone` is not satisfied
struct Log {
file: File,
}
fn main() {
let _ = Log {
file: File::open("/dev/null").unwrap(),
};
}File is not Clone because duplicating an operating system handle is a fallible operation (File::try_clone exists for that and returns a Result). Clone::clone cannot fail, so the standard library leaves the trait off. Mutable references (&mut T) are also not Clone, since two live &mut to one value would break the borrowing rules.
Deriving and hand-writing Clone are covered in their own chapters. For now, note that the trait is a normal trait. You can call .clone() on any value whose type implements it, and you can require it in generic code with a T: Clone bound.
Clone is not always a deep copy of everything
The name suggests a full duplicate, but the standard guidance is only that the result should be a value equivalent to the original. A type may share some state internally. Rc is the standard example: the clone is equivalent to the original because it refers to the same data. Types like channel senders (std::sync::mpsc::Sender) also clone into another handle on the same channel and not into a new channel.
When you see .clone() on an unfamiliar type, check its documentation to see which kind of clone it provides.
Method resolution and references
Because clone takes &self, calling it on a reference can behave in a surprising way. Rust looks for a clone method on the type of the receiver first. If you have a &String, the method String::clone matches with &self being &String, so the result is a String:
fn show(s: &String) {
let owned: String = s.clone();
println!("{owned}");
}
fn main() {
show(&String::from("hi"));
}That is usually what you want. The surprise comes when the type behind the reference does not implement Clone. Then Rust falls back to Clone for &T, which copies the reference and not the value:
struct Token(u32);
fn main() {
let t = Token(7);
let r = &t;
let c = r.clone(); // c is a &Token, not a Token
println!("{}", c.0);
}Here Token has no Clone implementation, so r.clone() compiles and returns another &Token. There is no error, but also no duplicate. Clippy reports this as the clippy::clone_on_ref_ptr-style family of warnings in some configurations, and the compiler's type annotation is the best check: write let c: Token = r.clone(); and you get an error if no real clone exists.
When cloning is the right tool
Cloning is not a failure. It is the right choice in several common situations.
- You need an owned copy that outlives the original, for example to send a value to another thread or store it in a struct.
- You need to modify a copy while keeping the original unchanged.
- The value is small, so the allocation cost does not matter.
- The type is a shared pointer such as
RcorArc, and you actually want another owner.
It is the wrong tool when a reference would work. This function clones for no reason:
fn shout(name: String) -> String {
name.to_uppercase()
}
fn main() {
let name = String::from("ada");
let loud = shout(name.clone());
println!("{name} {loud}");
}Changing the parameter to &str removes the allocation at the call site:
fn shout(name: &str) -> String {
name.to_uppercase()
}
fn main() {
let name = String::from("ada");
let loud = shout(&name);
println!("{name} {loud}");
}The second version borrows name. The caller keeps ownership, and no extra buffer is created.
Cloning in loops and hot paths
Because each .clone() on a String or Vec allocates, the cost grows when it sits inside a loop. This code clones the whole list on every iteration:
fn main() {
let words = vec![String::from("a"), String::from("b"), String::from("c")];
for i in 0..words.len() {
let snapshot = words.clone();
println!("{} of {}", i, snapshot.len());
}
}Nothing here needs an owned copy. Using words.len() directly gives the same output without any allocation. When you find a clone in a loop, ask whether the loop body needs ownership or only a look at the data.
Summary of the model
Clone::clone(&self) -> Selfcreates a new, independent value and leaves the original untouched.- It is always explicit. The compiler does not call it for you.
- Its cost depends entirely on the type: trivial for integers, proportional to size for
StringandVec, constant forRcandArc. - Deriving requires every field to be
Clone. - Calling
.clone()through a reference to a non-Clonetype clones the reference, not the value.
Exercise
What does this program print, and how many heap allocations for string data does the clone call perform?
use std::rc::Rc;
fn main() {
let a = Rc::new(String::from("data"));
let b = a.clone();
println!("{}", Rc::strong_count(&b));
}
Show answer
It prints 2. The call to a.clone() performs no allocation for the string data. Rc::clone copies the pointer and increments the strong count, so a and b share one String.
Exercise
A function takes fn total_len(items: Vec<String>) -> usize, and a caller writes total_len(list.clone()) because it needs list afterwards. How can you remove the clone, and what changes in the signature?
Show answer
Change the parameter to borrow the data, for example fn total_len(items: &[String]) -> usize, and call total_len(&list). The function only reads the items, so it does not need ownership. The caller keeps list, and no vector or strings are allocated.