Reputation: 1096
Given this code:
trait Trait {}
struct Child;
impl Trait for Child {}
struct Father<'a> {
child: &'a Box<dyn Trait>,
}
impl<'a> Trait for Father<'a> {}
fn main() {
let child: Box<dyn Trait> = Box::new(Child {});
let father: Box<dyn Trait> = Box::new(Father { child: &child });
let grandf: Box<dyn Trait> = Box::new(Father { child: &father });
}
This code doesn't compile with Rust 1.30.0 and I'm getting the following error:
error[E0597]: `child` does not live long enough
--> src/main.rs:11:60
|
11 | let father: Box<dyn Trait> = Box::new(Father { child: &child });
| ^^^^^ borrowed value does not live long enough
12 | let grandf: Box<dyn Trait> = Box::new(Father { child: &father });
13 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
I can make the code compile by using child: &'a Box<dyn Trait + 'a>
, but I don't understand why this happens.
According to RFC 0599, the default object bound rules should read the type &'a Box<Trait>
as &'a Box<Trait + 'a>
. Instead, it is acting as it was &'a Box<Trait + 'static>
.
&'a Box<Trait + 'static>
as it seems?There is a key difference between this question and Why is adding a lifetime to a trait with the plus operator (Iterator<Item = &Foo> + 'a) needed?.
According to the RFC 0599 that was mentioned in the answer of that question, there is a difference between a &'a Box<SomeTrait>
type and just a Box<SomeTrait>
that makes them have different default lifetimes. So, in this case, per the RFC, I think the default lifetime of the boxed trait should be 'a
and not 'static
.
This means that either there is a newer RFC changing that specification of RFC 0599, or there is another reason for this code to not work.
In both cases, that answer from the other question would not apply to this one, and therefore, this is not a duplicated question.
Upvotes: 4
Views: 321
Reputation: 430634
These rules were adjusted by RFC 1156 (emphasis mine):
Adjust the object default bound algorithm for cases like
&'x Box<Trait>
and&'x Arc<Trait>
. The existing algorithm would default to&'x Box<Trait+'x>
. The proposed change is to default to&'x Box<Trait+'static>
.
Upvotes: 3