Rust 程式設計影片教程(進階)——026_3 高階 trait3

linghuyichong發表於2020-02-20

頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

github地址:https://github.com/anonymousGiga/learn_rus...

完全限定語法
(1)同名的方法

trait A{ 
    fn print(&self);
} 
trait B{ 
    fn print(&self); 
} 
struct MyType; 
impl A for MyType{ 
    fn print(&self) { 
        println!("A print for MyType");
    }
} 
impl B for MyType{ 
    fn print(&self) { 
        println!("B print for MyType"); 
    } 
} 
impl MyType{ 
    fn print(&self) { 
        println!("MyType");
    } 
}
fn main() {
    let my_type = MyType;
    my_type.print(); //等價於MyType::print(&my_type);
    A::print(&my_type);
    B::print(&my_type);
    println!("Hello, world!");
}

說明:上述例子中,方法獲取一個 self 引數,如果有兩個 型別 都實現了同一 trait,Rust 可以根據 self 的型別計算出應該使用哪一個 trait 實現。(使用my_type.print(),print方法根據裡面的self型別知道具體呼叫哪個方法)

(2)對關聯函式的完全限定語法
例子:

trait Animal { 
    fn baby_name() -> String;
} 
struct Dog; 
impl Dog { 
    fn baby_name() -> String { 
        String::from("Spot") 
    } 
} 
impl Animal for Dog { 
    fn baby_name() -> String { 
        String::from("puppy")
    } 
} 
fn main() { 
    println!("A baby dog is called a {}", Dog::baby_name());
    //println!("A baby dog is called a {}",     
    Animal::baby_name());//報錯,如何處理? 
}

正確的呼叫方式:

fn main() { 
    println!("A baby dog is called a {}", Dog::baby_name());
    println!("A baby dog is called a {}", 
            <Dog as Animal>::baby_name());//完全限定語法 
}

完全限定語法定義為:

<Type as Trait>::function(receiver_if_method, next_arg, ...);
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章