In the answer to this question there\'s a discussion of how to refer to trait objects held by structs which requires the following syntax:
struct Bar<\'a&
why the lifetime isn't for the object that the trait is a trait on
Because the reference to the trait object and the trait object itself might have different lifetimes. Here's an example of a trait that is implemented for a reference:
trait Quack {
fn quack(&self) { println!("Quack") }
}
impl<'a> Quack for &'a bool {}
struct MasterQuack<'a> {
q: &'a (Quack + 'a),
}
fn main() {
let a = true;
// a.quack(); // Nope, not defined
(&a).quack();
// MasterQuack {q: &a}; // Nope, this would be a reference to a boolean, which isn't Quack
MasterQuack {q: &&a};
}
One thing to note is that it's perfectly fine to have &'a (Trait + 'b)
- that is, a reference to a trait that itself has a / is a reference, and those lifetimes are different. You said as much with
Is there a case where the trait and the underlying object would have different lifetimes?
But it's more a case of "the underlying object has references with different lifetimes".
why can't Rust just do The Right Thing(tm)
As of RFC 599 this now compiles:
struct Bar<'a> {
foo: &'a Foo,
}