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

[第三章] 第92页 关于impl 特化 #260

Open jellybobbin opened 4 years ago

jellybobbin commented 4 years ago

页码与行数:

代码清单 3-78:(随书源码)

#![feature(specialization)]
struct Diver<T> {
    inner:T
}
trait Swimmer {
    fn swim(&self){
        println!("swimming")
    }
}
impl<T> Swimmer for Diver<T>{}
impl Swimmer for Diver<&'static str> {
    fn swim(&self){
        println!("drowning, help!")
    }
}
fn main(){
    let x = Diver::<&'static str> { inner: "Bob" };
    x.swim();    //drowning, help!
    let y = Diver::<String> { inner: String::from("Alice") };
    y.swim();    // swimming
}

错误信息:

   Compiling playground v0.0.1 (/playground)
error[E0520]: `swim` specializes an item from a parent `impl`, but that item is not marked `default`
  --> src/main.rs:12:5
   |
10 |   impl<T> Swimmer for Diver<T>{}
   |   ------------------------------ parent `impl` is here
11 |   impl Swimmer for Diver<&'static str> {
12 | /     fn swim(&self){
13 | |         println!("drowning, help!")
14 | |     }
   | |_____^ cannot specialize default item `swim`
   |
   = note: to specialize, `swim` in the parent `impl` must be marked `default`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0520`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

修改为如下:

#![feature(specialization)]
struct Diver<T> {
    inner:T
}
trait Swimmer {
    //如果是impl 特化, 此方法始终不会运行
    //fn swim(&self){
    //    println!("swimming")
    //}

    fn swim(&self);
}
impl<T> Swimmer for Diver<T>{
    //必须存在此default fn
    default fn swim(&self){
        println!("swimming")
    }
}
impl Swimmer for Diver<&'static str> {
    fn swim(&self){
        println!("drowning, help!")
    }
}
fn main(){
    let x = Diver::<&'static str> { inner: "Bob" };
    x.swim();    //drowning, help!
    let y = Diver::<String> { inner: String::from("Alice") };
    y.swim();    // swimming
}

在线测试

ZhangHanDong commented 4 years ago

@jellybobbin 感谢反馈