其他分享
首页 > 其他分享> > rust中trait简单的代码实现

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());
}

标签:String,author,trait,代码,pub,content,location,self,rust
来源: https://blog.csdn.net/qq_42874635/article/details/121034894