您的当前位置:首页正文

Rust学习───trait

来源:图艺博知识网

什么是trait?如果了解Java语言的话,你就可以把trait理解为Javainterface接口

  • 定义

    pub trait Summarizable 
    {
         fn summary(&self) -> String;
    }
    
    
  • 定义struct

    pub struct NewsArticle 
    {
        pub headline: String,
        pub location: String,
        pub author: String,
        pub content: String
    }
    
    
    
  • 实现trait

    impl Summarizable for NewsArticle 
    {
        fn summary(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
    
    
  • 调用

    fn main() {
        let article = NewsArticle {
            headline: String::from("headline"),
            location: String::from("location"),
            author: String::from("author"),
            content: String::from("content"),
        };
    
        println!("{}", article.summary());
    }
    
    
    
Top