Skip to content

Cannot declare const in function scope that depends on generic impl const #64201

Closed
@ObsidianMinor

Description

@ObsidianMinor

The compiler misreports the following as error 401, saying you can't use generic parameters from an outer function.

trait X {
    const Y: i32;
}

trait Z {
    fn a() -> i32;
}

struct B<T> {
    t: std::marker::PhantomData<T>
}

impl<T: X> Z for B<T> {
    fn a() -> i32 {
        const C: i32 = T::Y;

        C
    }
}
error[E0401]: can't use generic parameters from outer function
  --> src/lib.rs:15:24
   |
13 | impl<T: X> Z for B<T> {
   |      - type parameter from outer function
14 |     fn a() -> i32 {
   |        - try adding a local generic parameter in this method instead
15 |         const C: i32 = T::Y;
   |                        ^^^^ use of generic parameter from outer function

This is limiting because if you're implementing a trait like X over an external type like Vec there's no way to declare a const that depends on the impl generic type. You can't make the const in the function scope, you can't make it in the impl scope, and you can't make it outside of the impl block since it relies on the generic parameter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions