Why does the `Clone` of a fixed-size array require the `Copy` bound?

Arrays of sizes from 0 to 32 (inclusive) implement the Clone trait only if the element type T is bounded by Copy. What is the consideration for this requirement?

I assume it's because Clone can panic; if it does panic in the middle of cloning the elements of the array, that means you have half an uninitialised array, which can't be dropped correctly.

Presumably, it could be done with some unsafe trickery, but either no one's gone to the trouble, or it wasn't deemed to be worth it.

Thanks for your help! It seems that the Copy bound narrows the area where a fixed-size array can be used.

It can be Cloned safely with a macro that does [self[0].clone(), self[1].clone(), ...] though; rust already has to handle this properly in user code.

impl<T:Copy> Clone for [T; $N] {
    fn clone(&self) -> [T; $N] {
        *self
    }
}

That's dead simple, probably amounts to just a memcpy. With impl specialization, hopefully we could keep this one for T:Copy and have a more generic version for T:Clone.

There was some discussion a few weeks ago in the RFC repo. We basically came to the same conclusions mentioned above: (1) array impls are awful at the moment because of the lack of genericity over integers, (2) it's hard to write a macro that expands to the [self[0].clone(), ...] version, and (3) you can't do a loop version at the moment because of panic safety.

1 Like