Implementing a trait for reference and non reference types causes conflicting implementations

前端 未结 2 657
迷失自我
迷失自我 2021-01-14 02:46

I\'m trying to create a trait and provide one implementation for all non-reference types, and another for all reference types.

This fails to compile:



        
2条回答
  •  有刺的猬
    2021-01-14 03:32

    The reason for the Clone version works is because the types that the trait is being implemented for are no longer conflicting on the implementation.

    Take the first example and add a default implementation.

    trait Foo {
        fn hi(&self){
            println!("Hi");
        }
    }
    

    And then we implement Foo for all of type T with impl Foo for T {} this actually implements enough for us to use a reference to our types and use the Foo trait. For Example:

    fn say_hi<'a>(b: &'a mut Foo){
        b.hi();
    }
    
    fn main(){
        let mut five = 5;
    
        five.hi(); // integer using Foo
        say_hi(&mut five); // &'a mut Foo
    }
    

    To answer the second part of you question, you didn't need the second implement of impl<'a,T> Foo for &'a mut T {} because impl Foo for T {} was enough to give you what you were looking for.

    Now that we have seen that the first example works without the second implement it starts to make sense that the example using Clone works because you are implementing for a subset of types T that are Clone and a different subset of types &'a mut T that are Clone+static

提交回复
热议问题