走进Rust:trait

Rust大约 1742 字

注意

trait类似Java中的接口interface

定义trait

pub trait Summary {
    fn summarize(&self) -> String;
}
pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

let tweet = Tweet {
    username: String::from("horse_ebooks"),
    content: String::from("of course, as you probably already know, people"),
    reply: false,
    retweet: false,
};

println!("1 new tweet: {}", tweet.summarize());

默认实现

默认实现的方法无须再次impl

pub trait Summary {
    fn summarize(&self) -> String {
        String::from("(Read more...)")
    }
}

trait作为参数

面向接口编程。

pub fn notify(item: impl Summary) {
    println!("Breaking news! {}", item.summarize());
}

Trait Bound语法

由上述例子item: impl Summary转变而来的语法糖。参数为接口时,定义泛型。

pub fn notify<T: Summary>(item1: T, item2: T) {
    println!("Breaking news1! {}", item1.summarize());
    println!("Breaking news2! {}", item2.summarize());
}

通过 + 指定多个trait bound

参数为实现了SummaryDisplaytrait

pub fn notify(item: impl Summary + Display) {

}

通过+改写。

pub fn notify<T: Summary + Display>(item: T) {

}

通过 where 简化trait bound

通过+指定的多个trait bound

fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {

}

通过where改写。

fn some_function<T, U>(t: T, u: U) -> i32
    where T: Display + Clone,
          U: Clone + Debug
{

}

函数返回trait类型

Tweet为实现了Summary的结构体。

fn returns_summarizable() -> impl Summary {
    Tweet {
        username: String::from("horse_ebooks"),
        content: String::from("of course, as you probably already know, people"),
        reply: false,
        retweet: false,
    }
}
阅读 109 · 发布于 2020-07-22

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批