Rust 編程視頻教程(進(jìn)階)——026_4 高級(jí) trait4

視頻地址

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

源碼地址

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

講解內(nèi)容

1、父 trait 用于在另一個(gè) trait 中使用某 trait 的功能
有時(shí)我們可能會(huì)需要某個(gè) trait 使用另一個(gè) trait 的功能。在這種情況下,需要能夠依賴相關(guān)的 trait 也被實(shí)現(xiàn)。這個(gè)所需的 trait 是我們實(shí)現(xiàn)的 trait 的 父(超) trait(supertrait)。
(1)錯(cuò)誤例子:

use std::fmt;
trait OutPrint: fmt::Display { //要求實(shí)現(xiàn)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 模式用以在外部類(lèi)型上實(shí)現(xiàn)外部 trait
孤兒規(guī)則(orphan rule):只要 trait 或類(lèi)型對(duì)于當(dāng)前 crate 是本地的話就可以在此類(lèi)型上實(shí)現(xiàn)該 trait。一個(gè)繞開(kāi)這個(gè)限制的方法是使用 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);
}

說(shuō)明:
在上述例子中,我們?cè)?Vec<T> 上實(shí)現(xiàn) Display,而孤兒規(guī)則阻止我們直接這么做,因?yàn)?Display trait 和 Vec<T> 都定義于我們的 crate 之外。我們可以創(chuàng)建一個(gè)包含 Vec<T> 實(shí)例的 Wrapper 結(jié)構(gòu)體,然后再實(shí)現(xiàn)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容