Use Clone when you need to duplicate a Rust value explicitly: calling clone() produces another value. This differs from Copy, which lets the compiler copy eligible values automatically on assignment or when passing them by value. section 9.5 section 10.5
For a struct whose fields support it, #[derive(Clone)] provides the implementation without writing it by hand. You can then call clone() on an instance. section 2.2.5
use std::fmt::Debug;
#[derive(Clone, Debug, Default)]
struct Pumpkin {
mass: f64,
diameter: f64,
}
The struct derives Clone alongside Debug and Default. section 2.2.5
fn main() {
let big_pumpkin = Pumpkin {
mass: 50.,
diameter: 75.,
};
println!("Big pumpkin: {:?}", big_pumpkin);
println!("Cloned big pumpkin: {:?}", big_pumpkin.clone());
println!("Default pumpkin: {:?}", Pumpkin::default());
}
The call to big_pumpkin.clone() shows explicit duplication in use. section 2.2.5
Generic code can require cloning through a trait bound. In the linked-list item below, T: Clone + Debug states which capabilities the stored type must provide. section 2.1.6
#[derive(Clone)]
struct ListItem<T>
where
T: Clone + Debug,
{
data: Box<T>,
next: Option<Box<ListItem<T>>>,
}
The listing combines a derived Clone implementation with trait bounds on the generic parameter. section 2.1.6
Clone deliberately, not as a reflexive way around ownership or borrowing. Unnecessary clones can cost performance and memory; cloning can still be a simple choice for immutable data structures, particularly when measurements support it. section 10.5 section 10.10




