Skip to content

Confusing errors when using Self variants with lifetimes #69224

Open
@clarfonthey

Description

@clarfonthey

Minimal example, imagine that we have the following type:

enum MyCow<'a> {
    Owned(String),
    Borrowed(&'a str),
}

If the user returns Self variants, this fails:

impl<'a> MyCow<'a> {
    fn borrow(&self) -> MyCow<'_> {
        match self {
            Self::Owned(s) => Self::Borrowed(s),
            Self::Borrowed(s) => Self::Borrowed(s),
        }
    }
    fn own(&self) -> MyCow<'static> {
        match self {
            Self::Owned(s) => Self::Owned(s.clone()),
            Self::Borrowed(s) => Self::Owned(s.to_string()),
        }
    }
}

But the same code works when you change Self to MyCow!

impl<'a> MyCow<'a> {
    fn borrow(&self) -> MyCow<'_> {
        match self {
            Self::Owned(s) => MyCow::Borrowed(s),
            Self::Borrowed(s) => MyCow::Borrowed(s),
        }
    }
    fn own(&self) -> MyCow<'static> {
        match self {
            Self::Owned(s) => MyCow::Owned(s.clone()),
            Self::Borrowed(s) => MyCow::Owned(s.to_string()),
        }
    }
}

The real error here is that Self really represents MyCow<'a> and not MyCow<'_> or MyCow<'static>-, but the errors don't really relay this. Potentially linked issue: #30904 (has been fixed).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-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