Skip to content

Suggest Self::CONST when trying to use an associated constant lexically #107199

Closed
@kpreid

Description

@kpreid

Code

struct Foo;
// const A_CONST: usize = 1;
impl Foo {
    const A_CONST: usize = 1;
    fn foo() -> usize {
        // const A_CONST: usize = 1;
        A_CONST
    }
}

Current output

error[E0425]: cannot find value `A_CONST` in this scope
 --> src/lib.rs:7:9
  |
7 |         A_CONST
  |         ^^^^^^^ not found in this scope

Desired output

help: try referring to the associated constant: `Self::A_CONST`

Rationale and extra context

Associated constants work entirely differently from constants at a higher scope (module) or lower (function) which are looked up lexically — if either of the other two declarations in the sample code are uncommented, compilation succeeds. This may be surprising to beginners (example that inspired this post), and the “what they meant” is fairly obvious, so this should be a good opportunity to help in the error message.

Additionally, if the suggestion is machine-applicable then it can be used to help refactor code when a constant was intentionally converted into an associated constant.

Other cases

No response

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions