您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页Rust学习───trait

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

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务