Matching a generic parameter to an associated type in an impl

后端 未结 3 1537
眼角桃花
眼角桃花 2020-11-29 09:40

I have a trait with an associated type and a generic struct::

trait Generator {
    type Foo;
    fn generate(&self) -> Self::Foo;
}

struct Baz

        
3条回答
  •  囚心锁ツ
    2020-11-29 09:50

    The trick is to only have a single generic parameter:

    trait Generator {
        type Foo;
        fn generate(&self) -> Self::Foo;
    }
    
    struct Baz
    where
        G: Generator,
    {
        generator: G,
        vec: Vec,
    }
    
    impl Baz
    where
        G: Generator,
    {
        fn add_foo(&mut self) {
            self.vec.push(self.generator.generate());
        }
    }
    

    Since the vector will contain G::Foo, we can actually just say that.

    The Rust style is snake_case, so I updated that as well as made the type parameter G to help the reader.

提交回复
热议问题