How does trait specialization actually work?

别来无恙 提交于 2020-01-01 17:09:14

问题


I tried to specialize a trait, and it fails to compile because of "conflicting implementations". But my understanding of specialization is that more specific implementations should override more generic ones. Here is a very basic example:

mod diving {
    pub struct Diver<T> {
        inner: T
    }
}

mod swimming {
    use diving;
    pub trait Swimmer {
        fn swim(&self) {
            println!("swimming")
        }
    }

    impl<T> Swimmer for diving::Diver<T> {

    }
}

mod drowning {
    use diving;
    use swimming;
    impl swimming::Swimmer for diving::Diver<&'static str> {
        fn swim(&self) {
            println!("drowning, help!")
        }
    }
}

fn main() {
    let x = diving::Diver::<&'static str> {
        inner: "Bob"
    };
    x.swim()
}

The error is:

rustc 1.18.0 (03fc9d622 2017-06-06)
error[E0119]: conflicting implementations of trait `swimming::Swimmer` for type `diving::Diver<&'static str>`:
  --> <anon>:23:5
   |
15 | /     impl<T> Swimmer for diving::Diver<T> {
16 | |     
17 | |     }
   | |_____- first implementation here
...
23 | /     impl swimming::Swimmer for diving::Diver<&'static str> {
24 | |         fn swim(&self) {
25 | |             println!("drowning, help!")
26 | |         }
27 | |     }
   | |_____^ conflicting implementation for `diving::Diver<&'static str>`

I would have expected that the more specific drowning implementation with an actual type of &'static str would allow specialized implementation, but instead it fails to compile.


回答1:


Specialization is not yet stabilized. You need to use nightly build of Rust and enable specialization by adding #![feature(specialization)] in the first line.

Then you'll need to fix two minor errors in your code (private inner field and lack of use swimming::Swimmer;), but that is straightforward.

Final code



来源:https://stackoverflow.com/questions/44600646/how-does-trait-specialization-actually-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!