Created
December 9, 2015 21:54
-
-
Save chikoski/c4de1bc32ce8d32dedbd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(dead_code)] | |
struct Store { | |
name: String, | |
items: Vec<Item>, | |
} | |
#[derive(Debug)] | |
struct Item { | |
name: &'static str, | |
price: f32, | |
} | |
impl Store { | |
fn new(name: String) -> Store { | |
Store { | |
name: name, | |
items: vec![], | |
} | |
} | |
fn add_item(&mut self, item: Item) { | |
self.items.push(item); | |
} | |
fn price(&self, item_name: &str) -> Option<f32> { | |
for item in &self.items { | |
if item.name == item_name { | |
return Some(item.price); | |
} | |
} | |
None | |
} | |
fn total_price(&self, shopping_list: &[&str]) -> Option<f32> { | |
// Goal: compute the total price of all items in the shopping | |
// list. If any of the options are not present, return `None`. | |
let mut sum = 0.0; | |
for name in shopping_list{ | |
let value = self.price(name); | |
match value{ | |
Some(_) => sum += value.unwrap(), | |
None => return None | |
} | |
} | |
Some(sum) | |
} | |
} | |
fn build_store() -> Store { | |
let mut store = Store::new(format!("Rustmart")); | |
store.add_item(Item { name: "chocolate", price: 5.0 }); | |
store.add_item(Item { name: "socks", price: 23.0 }); | |
store.add_item(Item { name: "plush Mozilla dinosaur", price: 13.0 }); | |
store | |
} | |
#[test] | |
fn total_price() { | |
let store = build_store(); | |
let list = vec!["chocolate", "plush Mozilla dinosaur"]; | |
assert_eq!(store.total_price(&list), Some(18.0)); | |
} | |
#[test] | |
fn total_price_missing() { | |
let store = build_store(); | |
let list = vec!["chocolate", "plush Mozilla dinosaur", "fork and knife"]; | |
assert_eq!(store.total_price(&list), None); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment