rust

How do I clone structs in Rust without using either Copy or Clone?


How do I create deep copies of each of these three styles of structs?

// A unit struct
struct Thing;

// A tuple struct
struct Thingy(u8, i32);

// regular
struct Location {
    name: String,
    code: i32,
}

Can I do this without using either the Copy or Clone traits? If a struct is already defined and doesn't have these trait implemented, is there a work-around?

// without this:
#[derive(Copy, Clone)]
struct Location {
    name: String,
    code: i32,
}

Solution

  • A unit struct contains no data, so a "deep copy" would be just another instance of it: let thing_clone = Thing;

    For the other types, you'd just manually clone the fields and create a new object out of the cloned fields. Assuming there is a new method for both Thingy and Location:

    let thingy_clone = Thingy::new(thingy.0, thingy.1);
    
    let location_clone = Location::new(location.name.clone(), location.code);
    

    Note that I only explicitly wrote .clone() for the String field. That is because u8 and i32 implement Copy and will therefore be automatically copied, when needed. No explicit copying/cloning required.

    That said, it's definitely more idiomatic to use the Clone trait. If Thing, Thingy and Location are part of an external library, you could file a bug report, asking for Clone to be implemented for those structs.