liveBook · Manning

Copy

As explained in Idiomatic Rust

The Rust Clone trait defines explicit duplication of a value through its clone method.

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

How Idiomatic Rust covers it

How deep it goes
Defines Clone through its method, shows derivation and generic bounds, and cautions against overuse without detailing implementation internals.
Examples
Shows a derived Clone implementation on a struct, a clone() call, and a generic linked-list item bounded by Clone.
What it assumes
Assumes familiarity with Rust structs and ownership; briefly explains how trait bounds constrain generic parameters.
What you can do after
Apply it via Rust’s #[derive(Clone)] and clone(), while reconsidering duplication used merely to avoid borrowing.
How it connects
Connects Clone to Copy, ownership, borrowing, trait bounds, generics, and immutable data structures.

Also explained in

Compare how 5 books explain copy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.