Matching a generic parameter to an associated type in an impl

后端 未结 3 1514
眼角桃花
眼角桃花 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:43

    You could get rid of the generic argument B and instead of constraining B, directly pass A::Foo as the second generic argument to Baz, but I'm not sure if your actual problem matches the simplified example you showed.

    impl<A: Generator> Baz<A, A::Foo> {
        fn addFoo(&mut self)  {
            self.vec.push(self.generator.generate());
        }
    }
    
    0 讨论(0)
  • 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<G>
    where
        G: Generator,
    {
        generator: G,
        vec: Vec<G::Foo>,
    }
    
    impl<G> Baz<G>
    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.

    0 讨论(0)
  • 2020-11-29 09:52

    I must explain to the compiler that B is the same as A::Foo

    There is a special syntax for it:

    impl<A, B> Baz<A, B>
    where
        A: Generator<Foo = B>,
    {
        fn add_foo(&mut self) {
            self.vec.push(self.generator.generate());
        }
    }
    
    0 讨论(0)
提交回复
热议问题