Why must the associated type be specified in a collection of references to types implementing a trait?

前端 未结 3 1825
醉酒成梦
醉酒成梦 2020-12-11 17:31

Here is an offending example:

// Some traits
trait Behaviour {
    type Sub: SubBehaviour;
}
trait SubBehaviour {}

// Some implementations of these traits
s         


        
3条回答
  •  庸人自扰
    2020-12-11 17:53

    You need to specify the associated type of the trait (i.e. Behavior).

    When adding the associated type at all places, it compiles:

    struct Example<'a, S: SubBehaviour + 'a> {
        behaviours: Vec<&'a Behaviour>,
    }
    
    impl<'a, S: SubBehaviour> Example<'a, S> {
        fn add_behaviour>(&mut self, b: &'a T) {
            self.behaviours.push(b);
        }
    }
    

    See this in action on the Playground

提交回复
热议问题