Skip to content

Suggest Struct::<'_> instead of Self when lifetime does not match #101393

Open
@QuineDot

Description

@QuineDot

Heads-up: PR 100976 probably fixes this but I still felt its own issue was warranted (and didn't find an existing one).


Given the following code:

pub struct Path<'a> {
    string: &'a mut String,
}

impl<'a> Path<'a> {
    pub fn sub(&mut self) -> Path/*<'_>*/ {
        Self {
            string: self.string,
        }
    }
}

The current output is:

error: lifetime may not live long enough
 --> src/lib.rs:8:21
  |
5 | impl<'a> Path<'a> {
  |      -- lifetime `'a` defined here
6 |     pub fn sub(&mut self) -> Path/*<'_>*/ {
  |                - let's call the lifetime of this reference `'1`
7 |         Self {
8 |             string: self.string,
  |                     ^^^^^^^^^^^ this usage requires that `'1` must outlive `'a`

Ideally the output should look like:

7 |         Self {
   |         ^^^^ help: Consider replacing `Self` with `Path`

Programmers not-infrequently expect Self to act as a type constructor and not fully aliased type (including lifetimes). Using Path in this context infers the lifetime, whereas using Self make the lifetime exactly 'a.

Though I haven't included it in my example, consider also the case when Self is used as the return type.

Another recent URLO example which inspired this report.

The same error appears on stable, nightly, and beta. But see PR 100976 which may resolve this issue.

@rustbot label +A-lifetimes +A-suggestion-diagnostics +D-newcomer-roadblock

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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