Dzwebs.Net

撰写电脑技术杂文十余年

通过impl构造链式函数调用及使用match枚举struct中的字段

Admin | 2024-2-1 12:02:01 | 被阅次数 | 406

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

    如题所示,通过impl构造链式函数调用及使用match枚举struct中的字段

#[derive(Debug,Clone)]
struct Shopinfor{
name:String,
price:f32,
}
impl Shopinfor{
fn new(name:String,price:f32)->Self{
Shopinfor{
name:name,
price:price,
}
}
fn get_type(self)->Self{
let c = self.clone();
match self{
Self{name,..} if name.contains("菜") =>{
println!("蔬菜类");
c
}
Self{name,..} if name.contains("肉") =>{
println!("肉类");
c
}
_ =>{
println!("未知类型");
c
}
}
}
fn get_price_cmp(self)->Self{
let c = self.clone();
match self{
Self{price,..} if price>=15.0 =>{
println!("单价超过预期…");
c
}
_ =>{
println!("价格在预期内…");
c
}
}
}
}
fn main(){
let mut c: Vec<Shopinfor> = Vec::new();
let s1 = Shopinfor::new("白菜".to_string(),2.1);
let s2 = Shopinfor::new("青菜".to_string(),2.0);
let s3 = Shopinfor::new("猪肉".to_string(),26.3);
c.push(s1);
c.push(s2);
c.push(s3);
for e in c{
e.get_type().get_price_cmp();//链式调用
}


}
// 蔬菜类
// 价格在预期内…
// 蔬菜类
// 价格在预期内…
// 肉类
// 单价超过预期…


该杂文来自: 最新技术

上一篇:在rust中动态使用json添加键值对的方法

下一篇:rust使用env构造命令行的示例

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计