Sub topic 3
Clone: duplicating explicitly with .clone()
This chapter assumes you know Rust structs, enums, and traits, the basics of ownership and borrowing, and how to read compiler errors. You have seen that assigning a String moves it. Here you will learn how to make a real duplicate on purpose.
What Clone is
Clone is a trait in the standard library. A type that implements it provides a clone method. The method takes &self and returns a new, independent value of the same type.
pub trait Clone: Sized {
fn clone(&self) -> Self;
}Because clone borrows its receiver, the original stays valid. The call is always written out, so each duplication shows up in the source. Compare this with Copy, where duplication happens silently on assignment.
A first example
fn main() {
let s = String::from("hi");
let t = s.clone();
println!("{s} {t}");
}Both bindings are usable. s.clone() allocates a new heap buffer and copies the bytes into it. The two strings share nothing, so changing one never affects the other.
fn main() {
let original = vec![1, 2, 3];
let mut copy = original.clone();
copy.push(4);
println!("{:?} {:?}", original, copy);
}This prints [1, 2, 3] [1, 2, 3, 4].
Clone can be deep
A clone of a container clones what it owns. Cloning a Vec<String> allocates a new buffer for the vector and then clones every String inside it. Cloning a struct clones each field in turn. The cost grows with the amount of data, so .clone() can be expensive.
Clone is not always deep
Clone only promises an independent value, and it does not promise a copy of all the data behind it. Some types implement clone cheaply. Rc<T> and Arc<T> are the main examples. Cloning one copies the pointer and adds one to a reference count. The data itself is shared.
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. Writing Rc::clone(&a) instead of a.clone() is a common convention. It tells the reader that the call is a cheap pointer copy and not a deep copy.
Clone is an opt-in trait
Not every type implements Clone. If you call .clone() on a type without it, the compiler rejects the call.
struct Token(u32);
fn main() {
let t = Token(7);
// let u = t.clone(); // error: no method named `clone` found for struct `Token`
println!("{}", t.0);
}For your own types, the usual fix is #[derive(Clone)], which a later chapter covers. A derived Clone works only when every field is Clone.
Clone and moves
Cloning is the standard way to keep using a value after handing it to something that takes ownership.
fn consume(s: String) -> usize {
s.len()
}
fn main() {
let name = String::from("Ada");
let n = consume(name.clone());
println!("{name} {n}");
}This works, but it allocates. If consume only reads the string, taking &str avoids the copy entirely. Reach for .clone() when you really need two owners. Do not use it only to silence a borrow-checker error without understanding the error.
Clone as a supertrait of Copy
Copy requires Clone. The declaration is pub trait Copy: Clone. Every Copy type is therefore also Clone, and for such types .clone() produces the same result as a plain assignment. The next chapter compares the two traits side by side.
Exercise
You have let a = Rc::new(String::from("data")); let b = a.clone();. How many String heap buffers exist after the second line, and what does Rc::strong_count(&a) return?
Show answer
One String buffer exists, because cloning an Rc copies only the pointer and increments the count. Rc::strong_count(&a) returns 2.
Exercise
Why does let t = s.clone(); on a String leave s usable, while let t = s; does not?
Show answer
clone takes &self, so it only borrows s and returns a new, independent String. A plain assignment moves ownership into t, which invalidates s.