What Is the Clone Trait and When Should You Use It?

The Clone trait creates a deep copy of a value, allowing multiple owners of the same data in Rust.

The Clone trait allows you to create a deep copy of a value, enabling multiple owners of the same data without moving ownership. Use it when you need to duplicate a value that implements Clone, such as a String, to keep the original intact while using a copy elsewhere.

let s1 = String::from("hello");
let s2 = s1.clone();

println!("s1 = {s1}, s2 = {s2}");

In generic functions, you can require Clone using a where clause to ensure the type can be duplicated:

fn some_function<T>(t: &T) -> i32
where
    T: Clone,
{
    unimplemented!()
}

When parsing command-line arguments into a Config struct, clone() is used to copy String values from the arguments slice into the struct fields:

fn new(args: &[String]) -> Config {
    let query = args[1].clone();
    let file_path = args[2].clone();
    Config { query, file_path }
}