当前位置:网站首页>Rust Development -- the concept and application example of trait
Rust Development -- the concept and application example of trait
2022-07-20 23:39:00 【He who knows what comes will go against it】
Trait
One 、 Concept
1.Trait Concept
Trait It is the function of a certain type that can be shared with other types . It abstractly defines the sharing behavior between types ,Trait bounds It refers to that the generic type parameter is specified as a type that implements a specific behavior constraint .
2.Trait The role of
- Use as an interface .
- The type tag Copy,Sized, By type marking IDE Can recognize some fixed types of behavior .
- Generic qualification 、 Input and output parameters are used as generic restrictions .
- Abstract types are equivalent to dynamic language calls , Static call , Dynamic invocation 、 Dynamic distribution .
3. Concepts and C++ The virtual function of is almost , The difference is rust There is no concept of class inheritance .
One 、Trait As an interface
1.Trait The definition of
// Use keywords trait Put the method signatures together , To define a set of behaviors necessary to achieve a certain purpose
// Here we use the article as an example , All articles have titles and authors , Whether blog or thesis
pub trait Article
{
// Only method signature , No specific implementation , There can be multiple ways
fn digest(&self) ->String;
// Default implementation
fn aothor(&self)
{
println!(" Default implementation ");
}
}
2. Realization Trait
pub struct WeChatArticle
{
pub aothor : String,// author
pub title : String,// title
pub timestamp : String// Create timestamps
}
pub struct Blog
{
pub aothor : String,// author
pub title : String,// title
pub collect : u64// Number of collections
}
// Implement for type 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 Application ".to_string(),
collect: 20
};
println!("Blog aothor is {}",blog.digest());
}s
4.Trait Default implementation of
pub trait article
{
// This is Trait Default implementation of , If the type does not override this method , The default implementation is used
fn aothor(&self) ->String
{
self.aothor.clone()
}
fn title(&self) ->String;
}
Two 、Trai Use as a parameter
1. Pass in as a parameter
//item Is to implement the Article This Trait The type of
pub fn notify(item : impl Article)
{
print!("Article digest {} \n",item.digest());
}
Use
fn main()
{
let blog : Blog = Blog
{
aothor:"matt".to_string(),
title:" Blog posts ".to_string(),
collect: 20
};
let wechar :WeChatArticle = WeChatArticle
{
aothor:"matt".to_string(),
title:" WeChat official account ".to_string(),
timestamp:"1324111889".to_string()
};
notify(blog);
notify(wechar);
}
2. Generic formal writing
//item Is to implement the Article This Trait The type of , Generic writing is more friendly to incoming unused types
pub fn notify<T:Article>(item_1: T,item_2 : T)
{
print!("Article digest {} \n",item_1.digest());
}
3. Multiple Trait constraint
//item Is to implement the Article and Display Two Trait
pub fn notify<T:Article + Display>(item_1: T)
{
print!("Article digest {} \n",item_1.digest());
}
Use where Clause realization Trait constraint
pub fn notify<T,U>(item_1: T,item_2 : U)
where
T : Article + Display, //T To show these two Trait constraint
U : Clone + Debug,
{
print!("Article digest {} \n",item_1.digest());
}
3、 ... and 、 Realization Trait As return type
// Only the same type can be returned , An error will be reported if the code of an improper type is returned
pub fn notify( b : bool) -> impl Article
{
// This will give you an error
// if(true)
// {
// Blog
// {
// aothor:"matt".to_string(),
// title:" Blog posts ".to_string(),
// collect: 20
// }
// }
// else
// {
// WeChatArticle
// {
// aothor:"matt".to_string(),
// title:" WeChat official account ".to_string(),
// timestamp:"1324111889".to_string()
// }
// }
WeChatArticle
{
aothor:"matt".to_string(),
title:" WeChat official account ".to_string(),
timestamp:"1324111889".to_string()
}
}
边栏推荐
猜你喜欢
跳槽了...历经字节测试岗3轮面试,4个小时灵魂拷问,结局透心凉...
[Yugong series] July 2022 go teaching course 013 constant, pointer
ARM PWN基础教程
力扣第五天
将 Terraform 生态粘合到 Kubernetes 世界
微信小程序接入微信支付流程
移动端中的分辨率、视口与二倍图
【大规模训练】transformer 中的张量模型并行
Job hopping After 3 rounds of interviews for byte test post, 4 hours of soul torture, the ending is cool
[ROS] use of roslaunch
随机推荐
云图说丨数字资产链:您的数字资产产权保护神
Review and Reflection on the development of this round of market 2021-04-05
一篇文章带你快速学会Flex布局
antd的按需引入+自定义主题
【云原生】 iVX 低代码开发 引入腾讯地图并在线预览
【ROS】roslaunch的使用
给1万帧视频做目标分割,显存占用还不到1.4GB,代码已开源 | ECCV 2022
js截取字符串(3种方法)
宣布 .NET 7 预览版 6
高数_第2章多元函数微分学__求解条件极值的方法__拉格朗日乘数法
Simple Fibonacci
MySQL5.7 参数详解
性能测试学习之jmeter单场景使用示例
JVM memory model
High number_ Chapter 2 differential calculus of multivariate functions__ Method of solving conditional extremum__ Lagrange multiplier method
shell中的运算
力扣刷题每日一题
[ROS] topic based use
【Flink】转换算子 map
使用Flutter开发小程序+App)的一种组合思路