I have a struct that consists of a fixed-size byte array with 65536 elements.
I've implemented Clone on my struct naively — I create a new array and loop through the original, copying each element one-at-a-time. Is there a more efficient or idiomatic way of doing this that would essentially boil down to a memcpy?
Arrays of items that are Clone always implement Clone, so you can simply call .clone() on the array, or #[derive(Clone)] on the struct.
As of Rust 1.12, arrays only implement Clone for up to 32 items. However, arrays implement Copy for any number of items (despite Copy requiring Clone!). We can therefore make an implicit copy of the array in our implementation of Clone.
struct Foo {
b: [u8; 65536],
}
impl Clone for Foo {
fn clone(&self) -> Self {
Foo {
b: self.b
}
}
}
If you also want your struct to implement Copy, then you can also implement Clone::clone by just making a copy of self:
#[derive(Copy)]
struct Foo {
b: [u8; 65536],
}
impl Clone for Foo {
fn clone(&self) -> Self {
*self
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With