What expressions are allowed as the array length N in [_; N]?

As of Rust 1.24.1, the array length basically needs to either be a numeric literal or a “regular” constant that is a usize. There’s a small amount of constant evaluation that exists today, but it’s more-or-less limited to basic math.

a perfectly valid expression in other contexts, just not as a length parameter to an array

Array lengths don’t support generic parameters. (#43408)

this is not a particularly good error message

Error message should be improved for associated consts in array lengths (#44168)

I would expect some restriction akin to constexpr

This is essentially the restriction, the problem is that what is allowed to be used in a const is highly restricted at the moment. Notably, these aren’t allowed:

  • functions (except to construct enums or structs)
  • loops
  • multiple statements / blocks

Work on good constant / compile-time evaluation is still ongoing. There are a large amount of RFCs, issues, and PRs improving this. A sample:

  • Const fn tracking issue (RFC 911)
  • Allow locals and destructuring in const fn (RFC 2341)
  • Allow if and match in constants (RFC 2342)

Leave a Comment