Const generics issue

Hi all

I have following code.

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

const fn buf_len<const A: usize, const B: usize>() -> usize {
    // aligned buffer len
    let max = [A, B][(A < B) as usize];
    ((max + B - 1) / B) * B
}

struct Helper<const A: usize, const B: usize>();
impl<const A: usize, const B: usize> Helper<A, B> {
    const NN: usize = buf_len::<A, B>();
}

fn add<const N:usize, const M:usize>() -> usize {
    N+M
}

fn add2<const M:usize>() -> usize 
{
    const MM1:usize = Helper::<10,{ M }>::NN;
    const MM2:usize = Helper::<20,{ M }>::NN;
    
    add::<MM1, M>() + add::<MM2, M>()
}

I just get:

error[E0401]: can't use generic parameters from outer item
  --> src/lib.rs:22:37
   |
20 | fn add2<const M:usize>() -> usize 
   |               - const parameter from outer item
21 | {
22 |     const MM1:usize = Helper::<10,{ M }>::NN;
   |                                     ^ use of generic parameter from outer item
   |
   = note: a `const` is a separate item from the item that contains it

error[E0401]: can't use generic parameters from outer item
  --> src/lib.rs:23:37
   |
20 | fn add2<const M:usize>() -> usize 
   |               - const parameter from outer item
...
23 |     const MM2:usize = Helper::<20,{ M }>::NN;
   |                                     ^ use of generic parameter from outer item
   |
   = note: a `const` is a separate item from the item that contains it

For more information about this error, try `rustc --explain E0401`.
error: could not compile `playground` (lib) due to 2 previous errors

Is it possible to simplify / fix it somehow to make it build ?
Tried nightly without any success.

Playground is here - Rust Playground

BR,
Denis

I've got zero idea as to what you need this for, but you are doing way too much of an unnecessary generics dance.

This compiles, is equivalent, and doesn't need generics, the helper struct, or nightly.

It's just a simplified example for more complex code made for portable_simd.
Unfortunately I cannot use just const functions. Lanes is made const generic there.

I don't see the problem.

See Rust Playground

That error is entirely unrelated to whether the consts come from a parameter or a function. You are just missing some required constraints. This compiles.

2 Likes

Thanks. Your combination of const fn & bounds works fine.

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.