Rust development - the concept and application examples of Trait

Trait

1. Concept

1.Trait concept
Trait is what a certain type has and can share functions with other types. It abstracts the shared behavior between types. Trait bounds refers to the generic type parameter specified as a type that implements a specific behavioral constraint.
2. The role of traits

  • Used as an interface.
  • The type marks Copy, Sized, and the IDE can recognize some fixed types of behaviors through the type marks.
  • Generic constraints, input parameters, and output parameters act as generic constraints.
  • Abstract types are equivalent to dynamic language calls, static calls, dynamic calls, and dynamic distribution.
    3. The concept is similar to the virtual function of C++, the difference is that rust does not have the concept of class inheritance.

1. Use Trait as an interface

1. Definition of Trait

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

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

2. Implement Traits

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

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. The default implementation of Trait

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

2. Trai is used as a parameter

1. Passed in as parameters

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

use

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

insert image description here
2. Generic form writing

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

3. Multiple Trait constraints

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

Use where clause to implement Trait constraints

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

3. Implement Trait as the return type

//只能返回确定的同一种类型,返回不周类型会的代码会报错
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
おすすめ