Rust中的Trait

类似接口,但和php中的trait又有点不一样。

pub trait Summary {
    fn summarize(&self) -> String;
}

pub struct NewArticle {
    pub headline: String,
    pub author: 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)
    }
}

impl Summary for NewArticle {
    fn summarize(&self) -> String {
          format!("{}, by {}", self.headline, self.author)
    }
}

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

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

    let article = NewArticle {
    headline: String::from("all will be ok"),
    author: String::from("sky chan"),
    };

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

猜你喜欢

转载自www.cnblogs.com/aguncn/p/11409380.html