rust:trait

rust中的trait类似于c++中的虚函数。trait可以有默认实现,也可以没有默认实现,类似于c++中的虚函数和纯虚函数。trait和虚函数用来定义接口,规范接口,是实现多态的基础。

c++中的虚函数实现多态,通过继承的方式来实现;rust中trait实现多态,类似于组合的方式,更加分散。

1example

(1)trait xxx声明一个trait,一个trait中可以声明一个或者多个方法

(2)trait中的方法可以有默认实现,也可以没有默认实现;没有默认实现的trait,那么trait实现中必须得实现

(3)impl xxxtrait for xxx

rust 复制代码
pub trait Summary {
  fn summarize_author(&self) -> String;

  fn summarize(&self) -> String {
    format!("Read more from {}...", self.summarize_author())
  }
}


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

pub struct Tweet {
  pub username : String,
  pub content : String,
  pub author : String,
  pub reply : bool,
  pub retweet : bool
}

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

impl Summary for Tweet {
  fn summarize_author(&self) -> String {
    format!("{}",self.author)
  }

  fn summarize(&self) -> String {
    format!("summarize of Tweet {}", self.summarize_author())
  }
}

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

  let tweet = Tweet {
    username : String::from("tweet-username"),
    content : String::from("tweet-content"),
    author : String::from("tweet-author"),
    reply : false,
    retweet : false
  };
  println!("tweet: {}", tweet.summarize());
}

2trait约束

在泛型中约束类型。

rust 复制代码
fn largest<T: PartialOrd + Copy>(list : &[T]) -> T {
  let mut largest = list[0];

  for &item in list.iter() {
    if item > largest {
      largest = item;
    }
  }
  largest
}

fn main() {
  let number_list = vec![1,2,3,4,5];
  let result = largest(&number_list);
  println!("largest number {}", result);

  let char_list = vec!['a','b','c','d','e'];
  let result = largest(&char_list);
  println!("largest char {}", result);
}

3trait参数和返回值

report的形参是trait,make_news_article的返回值是trait。

rust 复制代码
pub trait Summary {
  fn summarize_author(&self) -> String;

  fn summarize(&self) -> String {
    format!("Read more from {}...", self.summarize_author())
  }
}


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

pub struct Tweet {
  pub username : String,
  pub content : String,
  pub author : String,
  pub reply : bool,
  pub retweet : bool
}

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

impl Summary for Tweet {
  fn summarize_author(&self) -> String {
    format!("{}",self.author)
  }

  fn summarize(&self) -> String {
    format!("summarize of Tweet {}", self.summarize_author())
  }
}

fn report(item : impl Summary) {
  println!("report {}", item.summarize());
}

fn make_news_article() -> impl Summary {
  NewsArticle {
    headline : String::from("news---headline1"),
    location : String::from("news-location1"),
    author : String::from("news-author1"),
    content : String::from("news-content1")
  }
}

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

  let tweet = Tweet {
    username : String::from("tweet-username"),
    content : String::from("tweet-content"),
    author : String::from("tweet-author"),
    reply : false,
    retweet : false
  };
  println!("tweet: {}", tweet.summarize());

  report(tweet);

  let news1 = make_news_article();
  report(news1);
}
相关推荐
liu****5 小时前
Qt进阶实战:事件处理、文件操作、多线程与网络编程全解析
开发语言·网络·数据结构·c++·qt
草原上唱山歌5 小时前
C++如何调用Python代码
开发语言·c++·python
木子啊5 小时前
PHP中间件:ThinkCMF 6.x核心利器解析
开发语言·中间件·php
崇山峻岭之间5 小时前
Matlab学习记录40
开发语言·学习·matlab
Java后端的Ai之路5 小时前
【Python教程11】-文件
开发语言·python
东东5165 小时前
OA自动化居家办公管理系统 ssm+vue
java·前端·vue.js·后端·毕业设计·毕设
先做个垃圾出来………5 小时前
SortedList(2)
开发语言
云栖梦泽5 小时前
易语言开发从入门到精通:补充篇·文件批量操作深度实战·常用格式处理·自动化脚本开发·性能优化
开发语言
程序员鱼皮5 小时前
前特斯拉 AI 总监:AI 编程最大的谎言,是 “提效”
前端·后端·ai·程序员·开发
Big Cole5 小时前
PHP面试题(核心基础篇:垃圾回收+自动加载)
android·开发语言·php