How to Clone and Copy Structs in Rust

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.