3

How come this works,

let a = Box::new([2; 10]);
println!( "foo {:?}", a );

But this doesn't,

let a = Box::new([2; 100]);
println!( "foo {:?}", a );

Why does an array's length determine the trait implementations? The error seems unrelated to the question. Conversely, how can achive the effect I desire with the above code.

The error is reproduced is:

error[E0277]: arrays only have std trait implementations for lengths 0..=32
 --> ./test.rs:4:27
  |
4 |     println!( "foo {:?}", a );
  |                           ^ the trait `std::array::LengthAtMost32` is not implemented for `[{integer}; 100]`
  |
  = note: required because of the requirements on the impl of `std::fmt::Debug` for `[{integer}; 100]`
  = note: required because of the requirements on the impl of `std::fmt::Debug` for `std::boxed::Box<[{integer}; 100]>`
  = note: required by `std::fmt::Debug::fmt`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • Does this answer your question? [Implement Debug trait for large array type](https://stackoverflow.com/questions/30901965/implement-debug-trait-for-large-array-type) – Ryan1729 May 01 '20 at 03:06
  • not really, I ask why in this question. Why is that this is a constraint? Why was length=32 picked? I want to understand it not just be told it's impossible. – Evan Carroll May 01 '20 at 03:07
  • 1
    Ah okay. There's a bit about the rationale for why some N was chosen on the [documentation for the array module](https://doc.rust-lang.org/std/primitive.array.html). I'm not sure there's a deeper reason for why 32 was chosen other than "it seems big enough most of the time". – Ryan1729 May 01 '20 at 03:10
  • @Ryan1729 thanks that actually had exactly what I wanted! – Evan Carroll May 01 '20 at 03:13

1 Answers1

6

From the docs on array

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.

This answers both of my questions,

  • Rust lacks generics of the size of an array type,
  • 32 was a just an accepted compromise and there is no strong technical reason for it. It seems as if this trait is named as such because it's applied with macro.

And from this question, there is no acceptable workaround for this. It's just a hard limitation.

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468