如题,使用RUST语言编写的超市购物简易结算。其中包括商品的添加及结算,主要学习struct和impl接口对应的各函数。
#[derive(Debug)]
struct Product{
id:i32,
name:String,
price:f32,
num:f32,
}
#[derive(Debug)]
struct Shoppingcart{
items:Vec<Product>,
}
impl Shoppingcart{
fn new()->Self{
Shoppingcart{items:vec![]}
}
fn addproduct(id:i32,name:String,price:f32,num:f32)->Product{
Product{id:id,name:name,price:price,num:num}
}
fn showeachproduct(&self){
for e in self.items.iter(){
println!("商品信息:{:?}",e);
}
println!("{}",getlines());
println!("一共购买了种 {} 商品",self.items.len());
println!("{}",getlines());
}
fn totalnum(&self)->f32{
let t = self.items.iter().fold(0.0, |sum,e|sum+e.price * e.num);
println!("应支付总额 {} ",t);
println!("{}",getlines());
t
}
}
fn main(){
let mut myshoppingcart = Shoppingcart::new();
let myproduct = Shoppingcart::addproduct(1,"白菜".to_string(), 2.5, 2.0);
myshoppingcart.items.push(myproduct);
let myproduct = Shoppingcart::addproduct(2,"西红柿".to_string(), 4.0, 3.0);
myshoppingcart.items.push(myproduct);
let myproduct = Shoppingcart::addproduct(3,"米线".to_string(), 2.0, 3.0);
myshoppingcart.items.push(myproduct);
let myproduct = Shoppingcart::addproduct(4,"洗涤剂".to_string(), 13.6, 2.0);
myshoppingcart.items.push(myproduct);
let myproduct = Shoppingcart::addproduct(4,"南瓜".to_string(), 2.1, 4.0);
myshoppingcart.items.push(myproduct);
myshoppingcart.showeachproduct();
myshoppingcart.totalnum();
}
fn getlines()->String{
let mut lines = String::new();
let n = 66;
for _ in 1..=n{
lines.push_str("-")
}
lines
}