Dzwebs.Net

撰写电脑技术杂文十余年

rust学习示例:超市购物简易结算

Admin | 2024-1-2 19:54:01 | 被阅次数 | 763

温馨提示!

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

    如题,使用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
}


该杂文来自: 最新技术

上一篇:rust impl构造链式函数调用的示例

下一篇:rust输出每种变量的数据类型

网站备案号:

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

版权属性:

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

联系方式:

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