Skip to content

Compile or improve error message for static Self #119936

Closed
@rdbo

Description

@rdbo

Code

impl MyStruct {
    fn instance() -> &'static Self {
        static MYSTRUCT: OnceLock<Self> = OnceLock::new();
        MYSTRUCT.get_or_init(|| Self { msg: "Hello world!" })
    }
}

Current output

Compiling playground v0.0.1 (/playground)
error[E0401]: can't use generic parameters from outer item
  --> src/main.rs:10:35
   |
8  | impl MyStruct {
   | ---- `Self` type implicitly declared here, by this `impl`
9  |     fn instance() -> &'static Self {
10 |         static MYSTRUCT: OnceLock<Self> = OnceLock::new();
   |                                   ^^^^
   |                                   |
   |                                   use of generic parameter from outer item
   |                                   refer to the type directly here instead

Desired output

It should either compile, or have a different message

Rationale and extra context

The message says use of generic parameter from outer item - refer to the type directly here instead
This makes you believe that Self is a generic type, but it isn't. MyStruct can also be known at compile time at doesn't have generics attached to it, so maybe it could even compile.

Other cases

Changing the `Self` to `MyStruct`, which is the same thing, will make the code compile.

Rust Version

$ rustc --version --verbose
rustc 1.75.0 (82e1608df 2023-12-21)
binary: rustc
commit-hash: 82e1608dfa6e0b5569232559e3d385fea5a93112
commit-date: 2023-12-21
host: x86_64-unknown-linux-musl
release: 1.75.0
LLVM version: 17.0.6

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsD-confusingDiagnostics: Confusing error or lint that should be reworked.T-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