Data Modeling Capstone
Nested Order Summary
Aggregate Child Records
Nested structs can represent parent and child records, while methods keep aggregate calculations near the data.
Program
Play the program to choose a quantity and compute an order total from its line items.
nested_order_summary.rs
struct LineItem {
name: &'static str,
quantity: u32,
price: u32,
}
struct Order {
id: u32,
items: Vec<LineItem>,
}
impl Order {
fn total(&self) -> u32 {
self.items.iter().map(|item| item.quantity * item.price).sum()
}
}
fn main() {
let quantity = ;
let order = Order {
id: 7,
items: vec![
LineItem { name: "book", quantity, price: 15 },
LineItem { name: "pen", quantity: 3, price: 2 },
],
};
let first = order.items[0].name;
let total = order.total();
println!("order={} first={} total={}", order.id, first, total);
}
struct LineItem {
name: &'static str,
quantity: u32,
price: u32,
}
struct Order {
id: u32,
items: Vec<LineItem>,
}
impl Order {
fn total(&self) -> u32 {
self.items.iter().map(|item| item.quantity * item.price).sum()
}
}
fn main() {
let quantity = ;
let order = Order {
id: 7,
items: vec![
LineItem { name: "book", quantity, price: 15 },
LineItem { name: "pen", quantity: 3, price: 2 },
],
};
let first = order.items[0].name;
let total = order.total();
println!("order={} first={} total={}", order.id, first, total);
}
struct LineItem {
name: &'static str,
quantity: u32,
price: u32,
}
struct Order {
id: u32,
items: Vec<LineItem>,
}
impl Order {
fn total(&self) -> u32 {
self.items.iter().map(|item| item.quantity * item.price).sum()
}
}
fn main() {
let quantity = ;
let order = Order {
id: 7,
items: vec![
LineItem { name: "book", quantity, price: 15 },
LineItem { name: "pen", quantity: 3, price: 2 },
],
};
let first = order.items[0].name;
let total = order.total();
println!("order={} first={} total={}", order.id, first, total);
}
nested structs
`Order` owns a vector of `LineItem` child records.
method
`total` keeps aggregate behavior attached to the model it summarizes.
aggregation
The iterator multiplies each quantity by price, then sums the line totals.