Open
Description
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.