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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知来者逆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值