Rust Reference ยท Core Traits
The Clone trait
Reference for the Rust Clone trait: clone and clone_from, #[derive(Clone)], shallow vs deep copies, Clone vs Copy, Rc clones and manual implementations.
Clone is the trait for making an independent duplicate of a value on request. Calling .clone() returns a new value of the same type; for owning types like String and Vec<T> that means allocating and copying the contents, while for Rc<T> it only bumps a counter.
Cloning is always explicit: Rust never inserts a .clone() for you. That visibility is deliberate, because duplicating a large structure can be expensive. Copy is the stricter, implicit cousin for simple bit-copyable types; every Copy type must also be Clone.
let a = String::from("hello"); let b = a.clone(); // a and b are separate allocations
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait Clone: Sized { fn clone(&self) -> Self; fn clone_from(&mut self, source: &Self) { *self = source.clone() } }
| Item | Description |
|---|---|
clone(&self) -> Self |
Returns a duplicate. Required method. |
clone_from(&mut self, source) |
Makes self a copy of source. Defaults to *self = source.clone(); types override it to reuse allocations (String, Vec). |
#[derive(Clone)] |
Clones every field; generic parameters get a T: Clone bound. |
Edge cases. clone takes &self, so it cannot fail; types where duplication can fail, like file handles, offer try_clone instead and do not implement Clone. &T is Copy/Clone (cloning the reference, not the value), but .clone() on &T where T: !Clone silently clones the reference, which surprises people: the compiler warns with noop_method_call. &mut T is not Clone.
Usage notes
- Implemented by almost all standard types: numbers,
bool,char,String,Vec,Box,Option,Result, tuples and arrays ofClonetypes,Rc,Arcand more. Not byMutex,Fileor&mut T. ClonevsCopy:Copymarks types a plain bit copy is valid for and makes copies implicit;Cloneis explicit and may do arbitrary work. A manualClonefor aCopytype should simply be*self.- Deep vs shallow:
Vec<String>::clonecopies every string.Vec<Rc<T>>::clonecopies only pointers and counts. - Do not clone to silence the borrow checker out of habit. Often a reference, a move,
Rcor restructuring is the right fix. It is fine for small data or at API boundaries. - Use
.cloned()/.copied()on iterators of references, andCowwhen you clone only on demand. - A derive on a struct with a
PhantomData<T>field addsT: Clone, which can be too strict; implementClonemanually in that case. dyn Traitobjects cannot callClonedirectly (it needsSized); add abox_clonemethod to your trait as a workaround.
Related
- Cow, Rc, Arc, PhantomData
- Tutorial: Copy and Clone, Ownership, Rc and Arc