Why is Clone not implemented for arrays?

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?


1 Like

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.

1 Like

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:


1 Like

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

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.


1 Like

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> {

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.

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.

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