4

I can print in Debug the following array:

fn main() {
    let array = [0; 5];
    println!("{:?}", array);
}

However, if the size is bigger, let's say it's 50, the trait std::fmt::Debug will not be implemented by default:

fn main() {
    let array = [0; 50];
    println!("{:?}", array);
}

Compilation error:

error[E0277]: the trait bound [{integer}; 50]: std::fmt::Debug is not satisfied

Why is the std::fmt::Debug trait not implemented for some sizes of arrays?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

1 Answers1

5

From https://doc.rust-lang.org/std/primitive.array.html:

Arrays of sizes from 0 to 32 (inclusive) implement the following traits if the element type allows it:

  • Clone (only if T: Copy)
  • Debug
  • IntoIterator (implemented for &[T; N] and &mut [T; N])
  • PartialEq, PartialOrd, Eq, Ord
  • Hash
  • AsRef, AsMut
  • Borrow, BorrowMut
  • Default

This limitation on the size N exists because Rust does not yet support code that is generic over the size of an array type. [Foo; 3] and [Bar; 3] are instances of same generic type [T; 3], but [Foo; 3] and [Foo; 5] are entirely different types. As a stopgap, trait implementations are statically generated up to size 32.

Arrays of any size are Copy if the element type is Copy. This works because the Copy trait is specially known to the compiler.

Alexander Torstling
  • 18,552
  • 7
  • 62
  • 74
  • 3
    I hope that 2017 will be the year were Rust gains integral generic parameters (I'd really like if it got MORE than just integrals, but integrals would be so helpful already). – Matthieu M. Dec 15 '16 at 11:44
  • 1
    https://github.com/rust-lang/rust/issues/44580 for the tracking issue. It's getting closer. – Alexander Torstling Jun 10 '19 at 12:12
  • There's also talk of having generic array implementations sooner, see https://github.com/rust-lang/rust/pull/60466 – Matthieu M. Jun 10 '19 at 13:11
  • One more year has passed. – Gurwinder Singh Jun 09 '20 at 04:10
  • 2
    With current rust version, the definition has changed to "Arrays of any size implement the following traits if the element type allows it: Debug, IntoIterator (implemented for &[T; N] and &mut [T; N]), PartialEq, PartialOrd, Eq, Ord, Hash, AsRef, AsMut, Borrow, BorrowMut", Only the Default trait is still limited to 32 element arrays. – Sascha Dec 13 '20 at 15:28