Const generic array sizes as its own mini-stabilization?

   Compiling playground v0.1.0 (/home/eeeeeee/playground)
error: constant expression depends on a generic parameter
  --> src/main.rs:32:18
   |
32 |     let _f = [0; T::VALUE];
   |                  ^^^^^^^^
   |
   = note: this may fail depending on what value the parameter takes

Assuming T::VALUE is declared to be usize, is it actually possible for this to fail? AFAIK all usize are valid array sizes in Rust, including 0. Would it be possible to narrowly stabilize just using generic usize for array sizes? This combined with const declarations for associated consts already being allowed to have complex expressions would give me 99% of what I want for low level programming.

1 Like

I don't think it can fail, and I think I've already seen an issue about this (using associated constants in const generics) somethere on Rustʼs Github. Const generics are still WIP, I won't be surprised if we eventually get this.

1 Like

I know it's in the works eventually, I'm just wondering if we can get a big chunk of the value without waiting on the full feature by just stabilizing this particular use case.

Well yes, actually, depending how you look at it. Objects cannot be larger than isize::MAX bytes (see offset & similar's safety sections), so something like [0_u8; usize::MAX] will fail.

(There's open conversation about where exactly it makes sense for such errors to happen, but that's part of why this isn't allowed yet.)

4 Likes

TIL objects can be at most isize::MAX bytes :slight_smile:

Interesting. Rust already compromised on overflow/underflow checking with having it only be checked at runtime and only in debug builds, b/c without fancy things like dependent typing it's not practical to do real static checking. With const fn it seems like the same problem will exist at compile time now, and if "runtime" checking was the practical answer before it seems like it should be again here. It would mean sometimes you could get the sort of compile time backtraces C++ is infamous for, but I think I could live with that if it's only ever due to underflow/overflow or exceeding isize::MAX on array size.