Explicit lifetime declarations in trait objects held by structs

寵の児 提交于 2019-11-29 10:56:30

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,
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!