Explicit lifetime declarations in trait objects held by structs

后端 未结 1 1742
臣服心动
臣服心动 2020-12-19 09:40

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&         


        
相关标签:
1条回答
  • 2020-12-19 10:18

    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,
    }
    
    0 讨论(0)
提交回复
热议问题