Created
May 9, 2016 07:05
-
-
Save complxalgorithm/92f39a0a513a3ba4c410d89da31caae9 to your computer and use it in GitHub Desktop.
Rust program to demonstrate map; goes through all added contacts and calls them, with each calling outputting a saying.
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
use std::collections::HashMap; | |
fn call(number: &str) -> &str { | |
match number { | |
"798-1364" => "We're sorry, the call cannot be completed as dialed. | |
Please hang up and try again.", | |
"645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred. | |
What can I get for you today?", | |
_ => "Hi! Who is this again?" | |
} | |
} | |
fn main() { | |
let mut contacts = HashMap::new(); | |
contacts.insert("Daniel", "798-1364"); | |
contacts.insert("Ashley", "645-7689"); | |
contacts.insert("Katie", "435-8291"); | |
contacts.insert("Robert", "956-1745"); | |
// Takes a reference and returns Option<&V> | |
match contacts.get(&"Daniel") { | |
Some(&number) => println!("Calling Daniel: {}", call(number)), | |
_ => println!("Don't have Daniel's number."), | |
} | |
// `HashMap::insert()` returns `None` | |
// if the inserted value is new, `Some(value)` otherwise | |
contacts.insert("Daniel", "164-6743"); | |
match contacts.get(&"Ashley") { | |
Some(&number) => println!("Calling Ashley: {}", call(number)), | |
_ => println!("Don't have Ashley's number."), | |
} | |
contacts.remove(&("Ashley")); | |
// `HashMap::iter()` returns an iterator that yields | |
// (&'a key, &'a value) pairs in arbitrary order. | |
for (contact, &number) in contacts.iter() { | |
println!("Calling {}: {}", contact, call(number)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment