Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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,
}
like image 556
PrinceCornNM Avatar asked Aug 10 '26 20:08

PrinceCornNM


1 Answers

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.

like image 67
kangalio Avatar answered Aug 13 '26 18:08

kangalio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!