Using generics const expressions

Hi,

I tried the nightly feature using generic const expressions, but I get the following error message. When I add the where clause also to the function "g" it works fine. But why do I have to add the clause there as well?

error: unconstrained generic constant
  --> src/main.rs:11:25
   |
11 |     use_generic_array::<N>();
   |                         ^
   |
note: required by a bound in `use_generic_array`
  --> src/main.rs:3:12
   |
2  | fn use_generic_array<const N: usize>() -> usize
   |    ----------------- required by a bound in this function
3  | where [(); N + 1]: {
   |            ^^^^^ required by this bound in `use_generic_array`
help: try adding a `where` bound
   |
9  | fn g<const N: usize>() where [(); N + 1]:
   |                        ++++++++++++++++++
#![feature(generic_const_exprs)]
fn use_generic_array<const N: usize>() -> usize
where [(); N + 1]: {
    let data: [usize; N + 1] = [0; N + 1];
    // ... do other code
    return 5;
}

fn g<const N: usize>() /* where [(); N + 1]: adding this. The compilation works fine */
{
    use_generic_array::<N>();
}

pub fn main() { 
   g::<5>(); 
 }

This compiles:

Edit: Whoops, didn't read your post thoroughly enough. Note that generic bounds propagate everywhere. This is not special to const generics. This doesn't work either:

fn foo<T: std::fmt::Debug>(t: T) {
    println!("{t:?}");
}

fn bar<T>(t: T) {
    foo::<T>(t);
}

pub fn main() {
    bar::<u8>(0);
}

Playground.

Arrays can't be arbitrarily large; every object in Rust must have at most isize::MAX bytes.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.