ZhangHanDong / tao-of-rust-codes

《Rust编程之道》随书源码
https://ruststudy.github.io/tao_of_rust_docs/tao_of_rust/
MIT License
1.18k stars 170 forks source link

第三种trait_objec中static_dispatch<T>(t: &T) where T: Bar有问题 #299

Closed DaviRain-Su closed 4 years ago

DaviRain-Su commented 4 years ago

https://github.com/ZhangHanDong/tao-of-rust-codes/blob/809fcc80408b848824bd3fa5b3b0fb45a578436f/src/ch03/abstract_type.rs#L24-L42

pub fn trait_object() {
    #[derive(Debug)]
    struct Foo;
    trait Bar {
        fn baz(&self);
    }
    impl Bar for Foo {
        fn baz(&self) { println!("{:?}", self) }
    }
    fn static_dispatch<T>(t: &T) where T:Bar { 
        t.baz();
    }
    fn dynamic_dispatch(t: &Bar) {
        t.baz();
    }
    let foo = Foo;
    static_dispatch(&foo);
    dynamic_dispatch(&foo);
}

这里的 fn static_dispatch<T>(t: &T) where T: Bar {}应该改为 fn static_dispatch<T>(t: T) where T: Bar{} 这里做的 triat 限定,不应该使用引用把,要不这里是不是就和 triat 对象一样了呢?

pub fn trait_object() {
    #[derive(Debug)]
    struct Foo;
    trait Bar {
        fn baz(&self);
    }
    impl Bar for Foo {
        fn baz(&self) { println!("{:?}", self) }
    }
    fn static_dispatch<T>(t: T) where T:Bar {
        t.baz();
    }
    fn dynamic_dispatch(t: &Bar) {
        t.baz();
    }
    let foo = Foo;
    static_dispatch(foo);
    let foo = Foo;
    dynamic_dispatch(&foo);
}