Skip to content

"consider adding an explicit lifetime bound `R: 'static" suggestion is misleading #41966

@stepancheg

Description

@stepancheg

Consider an (incorrect) code:

trait Foo {}

struct Bar<R>(R);

impl<R> Foo for Bar<R> {
}

fn bb<R>(r: R) -> Box<Foo> {
    Box::new(Bar(r))
}

fn main() {
    let a = 10;
    let _b = bb(&a);
}

Rustc suggests:

consider adding an explicit lifetime bound `R: 'static`

This suggestion R: 'static is not good enough, code still won't compile.

The problem is that suggestion is misleading, because proper fix should be

fn bb<'r, R : 'r>(r: R) -> Box<Foo + 'r> { ... }

People who don't understand lifetimes well (like me), could stuck after adding 'static bound.

So better suggestion could be something like:

consider adding an explicit lifetime bound `R: 'static`,
or lifetime parameter `<'r, R: 'r> ... -> ... Trait + 'r`

or do not mention 'static at all:

consider adding an explicit lifetime bound to `R`

And also, I think, E0310 could have an example with non-static lifetime bound.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-dyn-traitArea: trait objects, vtable layoutA-lifetimesArea: Lifetimes / regionsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-papercutDiagnostics: An error or lint that needs small tweaks.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