Skip to content

Hint for missing lifetime bound on trait object is missing if type alias is used #103582

Open
@leo60228

Description

@leo60228

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a0979812dc1acbc732481dd2d3185637

trait Greeter {
    fn greet(&self);
}

type BoxedGreeter = Box<dyn Greeter>;

struct FixedGreeter<'a>(pub &'a str);

impl Greeter for FixedGreeter<'_> {
    fn greet(&self) {
        println!("{}", self.0)
    }
}

struct Greetings(pub Vec<String>);

impl Greetings {
    pub fn get(&self, i: usize) -> BoxedGreeter {
        Box::new(FixedGreeter(&self.0[i]))
    }
}

The current output is:

error: lifetime may not live long enough
  --> src/lib.rs:19:9
   |
18 |     pub fn get(&self, i: usize) -> BoxedGreeter {
   |                - let's call the lifetime of this reference `'1`
19 |         Box::new(FixedGreeter(&self.0[i]))
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static`

However, by removing the type alias: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=bfde1cf5c8a72349b117aa21bbd61c3d

trait Greeter {
    fn greet(&self);
}

struct FixedGreeter<'a>(pub &'a str);

impl Greeter for FixedGreeter<'_> {
    fn greet(&self) {
        println!("{}", self.0)
    }
}

struct Greetings(pub Vec<String>);

impl Greetings {
    pub fn get(&self, i: usize) -> Box<dyn Greeter> {
        Box::new(FixedGreeter(&self.0[i]))
    }
}

The output looks like this, which is much more helpful:

error: lifetime may not live long enough
  --> src/lib.rs:17:9
   |
16 |     pub fn get(&self, i: usize) -> Box<dyn Greeter> {
   |                - let's call the lifetime of this reference `'1`
17 |         Box::new(FixedGreeter(&self.0[i]))
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static`
   |
help: to declare that the trait object captures data from argument `self`, you can add an explicit `'_` lifetime bound
   |
16 |     pub fn get(&self, i: usize) -> Box<dyn Greeter + '_> {
   |                                                    ++++

Without the hint, this error isn't very helpful for beginners, as it doesn't do anything to explain why '1 must outlive 'static. It would be helpful if a similar hint could be provided when a type alias is used.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-dyn-traitArea: trait objects, vtable layoutA-lifetimesArea: Lifetimes / regionsD-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.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