I'm trying to implement something that looks like this minimal example:
trait Bar<T> {}
struct Foo<T> {
data: Vec<Box<Bar<T>>>,
}
impl<T> Foo<T> {
fn add<U: Bar<T>>(&mut self, x: U) {
self.data.push(Box::new(x));
}
}
Since Rust defaults to (as far as I can tell) pass-by-ownership, my mental model thinks this should work. The add
method takes ownership of object x
and is able to move this object into a Box
because it knows the full type U
(and not just trait Bar<T>
). Once moved into a Box
, the lifetime of the item inside the box should be tied to the actual lifetime of the box (e.g., when pop()
ed off the vector the object will be destroyed).
Clearly, however, the compiler disagrees (and I'm sure knows a bit more than I...), asking me to consider adding a 'static
lifetime qualifier (E0310). I am 99% sure that's not what I want, but I'm not exactly sure what I'm supposed to do.
To clarify what I'm thinking and help identify misconceptions, my mental model, coming from a C++ background, is:
Box<T>
is essentiallystd::unique_ptr<T>
- Without any annotations, variables are passed by value if
Copy
and rvalue-reference otherwise - With a reference annotation,
&
is roughlyconst&
and&mut
is roughly&
- The default lifetime is lexical scope
Check out the entire error:
Specifically, the compiler is letting you know that it's possible that some arbitrary type
U
might contain a reference, and that reference could then become invalid:That would be Bad News.
Whether you want a
'static
lifetime or a parameterized lifetime is up to your needs. The'static
lifetime is easier to use, but has more restrictions. Because of this, it's the default when you declare a trait object in a struct or a type alias:However, when used as an argument, a trait object uses lifetime elision and gets a unique lifetime:
These two things need to match up.
or
Yes it is. The compiler does not want a
&'static
reference, it wantsU: 'static
.Having
U: 'static
means thatU
contains no references with a lifetime less than'static
. This is required because you want to put aU
instance in a structure without lifetimes.