error[E0401]: can't use generic parameters from outer function

Hey yall

I have the following bit of code from a current project. It works if I change const SCALING to let scaling. Two questions:

  1. Is rust not able to do const computations with const generics?
  2. Can anyone explain me the error message? It's kind of confusing in this context and the explanations seem to point to the case where you try to reuse a generic as a type in the definition of an inner function or type.
type Float = f32;
type SpaceCoordinate = Float;
type GridCoordinate = usize;
const MIN: Float = -1.;
const MAX: Float = 1.;

fn main() {
    let a: SpaceCoordinate = 12.;
    let b: GridCoordinate = transform::<4>(a);
}

fn transform<const N_GRID: usize>(coord: SpaceCoordinate) -> GridCoordinate {
    const SCALING: Float = N_GRID as Float / (MAX - MIN);
    ((coord * SCALING).floor() - (MIN * SCALING).floor()) as usize
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0401]: can't use generic parameters from outer function
  --> src/main.rs:13:28
   |
12 | fn transform<const N_GRID: usize>(coord: SpaceCoordinate) -> GridCoordinate {
   |                    ------ const parameter from outer function
13 |     const SCALING: Float = N_GRID as Float / (MAX - MIN);
   |                            ^^^^^^ use of generic parameter from outer function

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

(E0401)

Currently only on nightly, using the incomplete and experimental #[feature(generic_const_exprs)] :confused:

The error message is not the best, but items like fns and consts inside a function definition behave as if they were actually declared outside the function. The only difference is that their visibility is restricted to inside the containing function.

3 Likes

OK. So maybe it would make sense to add an example of const doing the same thing to the explanation? Does anyone know where to raise such a concern?

Concern about what, specificaly? Feature which is incomplete and is not supposed to work, really doesn't work as was explained when const generics MVP was stablized? Is that really something worth reporting?

I'm pretty sure developers know, that's precisely why they separated it and stabilized only one part of it!

No i mean an example in the rustc --explain E0401 for consts.

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.