trait

Rust Clone trait: explicit duplication

Clone supports explicit duplication, with behavior and cost determined by the type. Cloning String creates its own owned contents, but cloning a smart pointer may share the same data. clone_from may reuse destination resources when implemented to do so. Expected output (not executed): Tea / Tea with milk Why: The cloned String can be changed independently of the original. Common mistake: Assuming clone always performs a deep copy or is always cheap.

Formal Syntax & Structure

rust syntaxrust
pub trait Clone: Sized { fn clone(&self) -> Self; /* clone_from also provided */ }

Working Example

Example Snippetrust
fn main() {    let original = String::from("Tea");    let mut copy = original.clone();    copy.push_str(" with milk");    println!("{original} / {copy}");}
Rust Reference