Rust开发——Trait的概念与应用示例

Trait

一、概念

1.Trait概念
Trait 是某种类型具有哪些并且可以与其它类型共享的功能。它把类型间的共享行为进行抽象定义,Trait bounds是指泛型类型参数指定为实现了某种特定行为约束的类型。
2.Trait的作用

  • 作为接口使用。
  • 类型标记Copy,Sized,通过类型标记IDE可以识别一些固定类型的行为。
  • 泛型限定、入参和出参作为泛型限制。
  • 抽象类型相当于动态语言调用,静态调用,动态调用、动态分发。
    3.概念和C++的虚函数差不多,差异在于rust没有类继承的概念。

一、Trait做为接口使用

1.Trait的定义

//使用关键字trait把方法签名放在一起,来定义实现某种目的必须的一组行为
//这里使用文章做例子,所有的文章都有标题和作者,不管是博客还是论文
pub trait  Article
{
    
    
    //只有方法签名,没有具体实现,可以有多个方法
    fn digest(&self) ->String;

    //默认实现
    fn aothor(&self)
    {
    
    
      println!("默认实现");
    }
}

2.实现Trait

pub struct WeChatArticle
{
    
    
    pub aothor : String,//作者
    pub title : String,//标题
    pub timestamp : String//创建时间戳
}


pub struct Blog
{
    
    
    pub aothor : String,//作者
    pub title : String,//标题
    pub collect : u64//收藏个数
}


//为类型实现trait
impl Article for Blog  
{
    
    
  fn digest(&self) ->String 
  {
    
    
    self.title.clone() + &self.title.clone() + &self.collect.to_string()
  } 
}

impl Article for WeChatArticle
{
    
    
  fn digest(&self) ->String 
  {
    
    
    self.title.clone() + &self.title.clone() + &self.timestamp.clone()
  } 
}

3.使用

use rust_demo::Blog;
use rust_demo::Article;
fn main() 
{
    
    
   let blog : Blog = Blog 
    {
    
     
        aothor:"matt".to_string(), 
        title:"Rust Trait 的应用".to_string(),
        collect: 20
     };
    println!("Blog aothor is {}",blog.digest());
}s

4.Trait的默认实现

pub trait  article
{
    
    
    //这个为Trait的默认实现,如果类型没有重写这个方法,则使用默认实现
    fn aothor(&self) ->String
    {
    
    
    	self.aothor.clone()
    }
    fn title(&self) ->String;
}

二、Trai作为参数使用

1.以参数的形式传入

//item是实现了Article这个Trait的类型
pub fn notify(item : impl Article)
{
    
    
  print!("Article digest {} \n",item.digest());
}

使用

fn main() 
{
    
    
   let blog : Blog = Blog 
    {
    
     
        aothor:"matt".to_string(), 
        title:"博客文章".to_string(),
        collect: 20
     };

    let wechar :WeChatArticle  = WeChatArticle
    {
    
     
        aothor:"matt".to_string(), 
        title:"微信公众号文章".to_string(),
        timestamp:"1324111889".to_string()
     };

     notify(blog);
     notify(wechar);
}

在这里插入图片描述
2.泛型形式写法

//item是实现了Article这个Trait的类型,泛型写法对传入不用的类型阅读更友好
pub fn notify<T:Article>(item_1: T,item_2 : T)
{
    
    
  print!("Article digest {} \n",item_1.digest());
}

3.多个Trait约束

//item是实现了Article和Display两个Trait
pub fn notify<T:Article + Display>(item_1: T)
{
    
    
  print!("Article digest {} \n",item_1.digest());
}

使用where子句实现Trait约束

pub fn notify<T,U>(item_1: T,item_2 : U)
    where
        T : Article + Display, //T要现了这两个Trait约束
        U : Clone + Debug,
{
    
    
  print!("Article digest {} \n",item_1.digest());
}

三、实现Trait作为返回类型

//只能返回确定的同一种类型,返回不周类型会的代码会报错
pub fn notify( b : bool) -> impl Article
{
    
    
    //这样会报错
    // if(true)
    // {
    
    
    //     Blog 
    //     { 
    //         aothor:"matt".to_string(), 
    //         title:"博客文章".to_string(),
    //         collect: 20
    //     }
    // }
    // else
    // {
    
    
    //     WeChatArticle
    //     { 
    //         aothor:"matt".to_string(), 
    //         title:"微信公众号文章".to_string(),
    //         timestamp:"1324111889".to_string()
    //     }
    // }
    WeChatArticle
    {
    
     
        aothor:"matt".to_string(), 
        title:"微信公众号文章".to_string(),
        timestamp:"1324111889".to_string()
    }
}

猜你喜欢

转载自blog.csdn.net/matt45m/article/details/125642336