Skip to content

Instantly share code, notes, and snippets.

@complxalgorithm
Created May 9, 2016 07:05
Show Gist options
  • Save complxalgorithm/92f39a0a513a3ba4c410d89da31caae9 to your computer and use it in GitHub Desktop.
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.
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