Issue
This Content is from Stack Overflow. Question asked by Florian
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() {}
Solution
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.
This Question was asked in StackOverflow by Florian and Answered by Chayim Friedman It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.