rust中trait简单的代码实现


// 定义一个trait
pub trait Summary {
    fn summarize(&self) -> String;
}

pub struct NewsArticle {
    pub headlie: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle{
    fn summarize(&self) -> String{
        format!("{}-{}-{}-{}", self.headlie, self.location, self.author, self.content)
    }
}

pub struct Tweet{
    pub name: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for Tweet{
    fn summarize(&self) -> String{
    	// 不能单独返回self.name,违反垂直引用
        format!("{}-{}-{}-{}", self.name, self.location, self.author, self.content)
    }
}


fn main() {
    let tweet = NewsArticle{
        headlie: String::from("baixiaobai"),
        location: String::from("baixiaohei"),
        author: String::from("baixiaolan"),
        content: String::from("baixiaozi"),
    };

    println!("调用结果是-{}", tweet.summarize());
}

上一篇:整合Spring Cloud Stream Binder与GCP Pubsub进行消息发送与接收


下一篇:哔哩哔哩 PHP新番推荐 获取信息