Let's say I've this playground code:
#[derive(Clone, Debug)]
struct Delivery<'a> {
customer: &'a str,
location: &'a str,
item: &'a str,
date: &'a str,
quantity: u64
}
fn main() {
let mut delivery: Vec<Delivery> = Vec::new();
delivery.push(Delivery { customer: "Hasan", location: "JO",
item: "xyz", date: "1/1/2019", quantity: 20});
delivery.push(Delivery { customer: "Hasan", location: "SA",
item: "xyz", date: "1/1/2019", quantity: 30});
let hasan_deliveries: Vec<Delivery> = delivery
.into_iter()
.filter(|d| d.customer == "Hasan")
.collect();
println!("Total deliveries to: {}, are: {}",
hasan_deliveries[0].customer,
hasan_deliveries[0].quantity);
}
The output will be:
Total deliveries to: Hasan, are: 20
I want to be able to get:
Total deliveries to: Hasan, are: 50
And avoid collecting hasan_deliveries
as a Vec
, as actually the returned type should be Delivery
where a kind of grouping is done,
I was able to return the total only, as:
let sum: u64 = delivery.into_iter()
.filter(|d| d.customer == "Hasan")
.fold(0, |mut sum, d| {sum += d.quantity; sum});
println!("Total deliveries are: {}", sum);
This returned:
Total deliveries are: 50
But I need a kind of mix, I need the return to be a struct of proper grouping, and summation, as SQL