Use the .clone() method to create a deep copy of a struct or value that implements the Clone trait.
Use the .clone() method to create a deep copy of a struct or value that implements the Clone trait.
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {s1}, s2 = {s2}");
For custom structs, implement the Clone trait manually or use the #[derive(Clone)] attribute to generate the implementation automatically.
Cloning creates a completely independent copy of your data, so changes to one do not affect the other. Think of it like photocopying a document: you now have two separate papers, and writing on one won't change the other. You use this when you need to keep the original data safe while also using a copy elsewhere in your program.