Rust 程式設計視訊教程(進階)——026_4 高階 trait4

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 用於在另一個 trait 中使用某 trait 的功能
有時我們可能會需要某個 trait 使用另一個 trait 的功能。在這種情況下,需要能夠依賴相關的 trait 也被實現。這個所需的 trait 是我們實現的 trait 的 父(超) trait(supertrait)。
(1)錯誤例子:

use std::fmt;
trait OutPrint: fmt::Display { //要求實現DisPlay trait
    fn out_print(&self) {
        let output = self.to_string();
        println!("output: {}", output);
    }
}
struct Point {
    x: i32,
    y: i32,
}
impl OutPrint for Point {}
fn main() {
    println!("Hello, world!");
}

(2)正確例子:

use std::fmt;
trait OutPrint: fmt::Display {
    fn out_print(&self) {
        let output = self.to_string();
        println!("output: {}", output);
    }
}
struct Point {
    x: i32,
    y: i32,
}
impl OutPrint for Point {}
impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}
fn main() {
    println!("Hello, world!");
}

2、newtype 模式用以在外部型別上實現外部 trait
孤兒規則(orphan rule):只要 trait 或型別對於當前 crate 是本地的話就可以在此型別上實現該 trait。一個繞開這個限制的方法是使用 newtype 模式(newtype pattern)。
例子:

use std::fmt;
struct Wrapper(Vec<String>);
impl fmt::Display for Wrapper {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}]", self.0.join(", "))
    }
}
fn main() {
    let w = Wrapper(vec![String::from("hello"),         
    String::from("world")]);
    println!("w = {}", w);
}

說明:
在上述例子中,我們在 Vec 上實現 Display,而孤兒規則阻止我們直接這麼做,因為 Display trait 和 Vec 都定義於我們的 crate 之外。我們可以建立一個包含 Vec 例項的 Wrapper 結構體,然後再實現。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

令狐一衝

相關文章