User Tools

Site Tools


accu.rs
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
 
struct Goods {
    name: String,
    cost: i64
}
 
impl Goods {
    fn new(name: String, cost: i64) -> Goods {
        return Goods { name: name, cost: cost }
    }
}
 
struct Accu {
    list: Vec<Goods>,
    total: i64
}
 
impl Accu {
    fn add(&mut self, t: Goods) {
        println!("add : {}, {}", t.name, t.cost);
        self.total += t.cost;
        self.list.push(t);
    }
}
 
fn main() {
    let w = Goods::new(String::from("whisky"), 20);
    let v = Goods::new(String::from("vodka"), 15);
 
    let mut a = Accu { list: Vec::new(), total: 0 };
    a.add(w);
    a.add(v);
    println!("summ:");
    let mut i: i32 = 1;
    for g in &a.list {
        println!(" {}: {}, {}", i, g.name, g.cost);
        i += 1;
    }
    println!("total cost: {}", a.total);
}

Out

$ ./accu
add : whisky, 20
add : vodka, 15
summ:
 1: whisky, 20
 2: vodka, 15
total cost: 35
$