Why do I get the error “the trait `Foo` is not implemented for `&mut T`” even though T implements the trait?

前端 未结 2 1350

I have this source:

pub fn draw(&self, font: &mut C, draw_state: &DrawState, transform: Matrix2d, g: &mut G)
where
    C: Charact         


        
2条回答
  •  攒了一身酷
    2020-12-16 20:26

    T, &T, and &mut T are all different types; and that means that &mut &mut T is likewise a different type. Traits are not automatically implemented for references to a type. If you wish to implement a trait for either of the references, you need to write it out explicitly.

    As an example, this exhibits the same problem:

    trait Foo {}
    
    #[derive(Debug, Copy, Clone)]
    struct S;
    impl Foo for S {}
    
    fn example(_: T)
    where
        T: Foo,
    {}
    
    fn main() {
        let mut s = S;
    
        example(s);
        example(&s);     // the trait bound `&S: Foo` is not satisfied
        example(&mut s); // the trait bound `&mut S: Foo` is not satisfied
    }
    

    Explicit implementations of the trait for the references solve the problem:

    impl<'a> Foo for &'a S {}
    impl<'a> Foo for &'a mut S {}
    

    In many cases, you can delegate the function implementations to the non-reference implementation.

    If this should always be true, you can make it so by applying it to all references to a type that implements a trait:

    impl<'a, T> Foo for &'a T where T: Foo {}
    impl<'a, T> Foo for &'a mut T where T: Foo {}
    

    If you don't have control over the traits, you may need to specify that you take a reference to a generic type that implements the trait:

    fn example(_: &mut T)
    where
        for<'a> &'a mut T: Foo,
    {}
    

    See also:

    • When should I not implement a trait for references to implementors of that trait?

提交回复
热议问题