Why is Clone not implemented for arrays?


#1

I’m puzzled at the following error, which is actually a fraction of a longer error message:

 error: the trait `core::clone::Clone` is not implemented for the type `[u8; 512]`

I am trying to derive Clone, and apparently clone isn’t implemented for an array of bytes. What could possibly be more cloneable?! Am I missing something?

David


#2

Because of lack of type level integers, most of traits are implemented in std upto [T, 32].
If you convert [u8; 512] to [u8] you should be able to clone it.


#3

That’s frustrating. Is there hope of this being fixed in the future? I much prefer static checks to runtime checks, and therefore prefer arrays to slices when I know the size at compile time. And having an arbitrary cutoff at 32 seems like very poor style, and likely to throw programmers off, who find that what works in prototype fails in practice. :frowning:

David


#4

When derive doesn’t work you can still implement Clone manually.


#5

I would say that it will definitely improve in the future. Type level integers or similar feature is desired by many for exactly this kind of situations. Just be patient.


#6

Meanwhile you can look at https://github.com/rust-lang/rust/blob/master/src/libcore/array.rs#L74 and try to repeat this, wrapping [T; 512] into a newtype to avoid type conformance checks, something along these lines:

use std::clone::Clone;
struct Arr512<T>([T; 512]);

impl<T: Copy> for Arr512<T> {
  fn clone(&self) -> Arr512<T> {
    Arr512(self.0)
  }
}

Of cause you will need to repeat other impls already present for some [T; N] in std, like impl<T> Deref for Arr512<T> { ... }, impl<T> Index for Arr512<T> etc, but it’s the way you can make it work for now.


#7

Thanks for the encouragement all. It will certainly help to be able to derive traits, as there’s a rather long list that I would have to implement myself (Clone, PartialEq, Eq, Debug, Hash, Ord and PartialOrd).

And I certainly look forward to have type-level integers.


#8

Actually Deref impl might be enough for most cases, because of autoderef magic feature.