2

I'm experimenting with const expressions and generics in Rust and stumbled across the following problem. When I want to use the const generic argument (here N) indirectly like for example N + 1, the compiler tells me that I need to add a "where-bound" like this one:

where [(); N + 1]:,.

I don't understand the meaning of this. To me it looks like a constraint that says: "There is an array of type "empty tuple / unit" and "N + 1" entries which is bound to (nothing; as there is nothing after the colon)".

Can anyone help me understand the parts of this constraint?

Minimal example:

#![allow(unused)]
#![allow(incomplete_features)]
#![feature(generic_const_exprs)]

struct Foo<const N: usize> {}

impl<const N: usize> Foo<N>
where
    [(); N + 1]:,
{
    const BAR: [u32; N + 1] = [0u32; N + 1];
}

fn main() {}
Florian
  • 78
  • 6

1 Answers1

4

When you have no trait bounds, the type is only required to be well-formed, i.e. able to exist.

This is used in generic_const_exprs because this type may not compile. If, for example, N is usize::MAX, then N + 1 will overflow and cause a compilation error. generic_const_exprs requires all potential errors to be reflected in the signature/header (and not just the body, see an other answer of mine for why). Because of that, the compiler requires you to repeat the expression in the header, to make sure that if the body can fail the header will also fail.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • 1
    I just learned that `[u32; usize::MAX]` is actually a valid type, in spite of having a size of `4 * usize::MAX`. – Sven Marnach Sep 19 '22 at 06:46
  • 1
    @SvenMarnach As a type it is valid, but in reality you cannot create values with more than `isize::MAX` bytes. – Chayim Friedman Sep 19 '22 at 06:52
  • 1
    Thank you! So the fact that the syntax reflects an array is not important but that the expression `N + 1` gets evaluated somehow to give it the possibility to fail. Ist that correct? – Florian Sep 19 '22 at 12:25
  • 2
    @Florian Technically, the type is evaluated, and that expression is just a part of it. – Chayim Friedman Sep 19 '22 at 14:41