如题所示,通过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();//链式调用
}
}
// 蔬菜类
// 价格在预期内…
// 蔬菜类
// 价格在预期内…
// 肉类
// 单价超过预期…