Do I have to implement a trait twice when implementing it for both reference and non-reference types?

后端 未结 3 760
心在旅途
心在旅途 2020-12-02 02:16

I want to implement a trait for both a for reference and non-reference type. Do I have to implement the functions twice, or this is not idiomatic to do so?

Here\'s t

3条回答
  •  甜味超标
    2020-12-02 02:43

    This is a good example for the Borrow trait.

    use std::borrow::Borrow;
    
    struct Bar;
    
    trait Foo {
        fn hi(&self);
    }
    
    impl> Foo for B {
        fn hi(&self) {
            print!("hi")
        }
    }
    
    fn main() {
        let bar = Bar;
        (&bar).hi();
        &bar.hi();
    }
    

提交回复
热议问题