I'm working my way through The Book and doing the last exercise under HashMap. The last exercise has really challenged me. Storing Keys with Associated Values in Hash Maps - The Rust Programming Language
I can't seem to find a way to sort or retrieve the company directory alphabetically. Here is the code that I've worked out, I'm limited to using the standard library and what The Book has taught me thus far. It looks like there are some crates out there, but I don't think I'm supposed to use them to learn how to do this:
/*
Using a hash map and vectors, create a text interface to allow a user to add
employee names to a department in a company. For example, “Add Sally to Engineering”
or “Add Amir to Sales.” Then let the user retrieve a list of all people in a
department or all people in the company by department, sorted alphabetically.
*/
let mut names = Vec::new();
let mut departments = Vec::new();
let mut directory = HashMap::new();
loop {
println!("Here are the departments in our company {:?}", departments);
println!("Do you want to add another [p]erson, view by [d]epartment, view [a]ll or [q]uit");
let mut yn = String::new(); //we put it hear so it clears at each loop
io::stdin().read_line(&mut yn).expect("failed to read line");
match yn.trim() {
"p" => {
let mut name = String::new();
let mut department = String::new();
println!("Input first and last name");
io::stdin()
.read_line(&mut name)
.expect("failed to read line");
println!("What department does {} work in?", name);
io::stdin()
.read_line(&mut department)
.expect("failed to read line");
departments.push(department.trim().to_string());
names.push(name.trim().to_string());
directory
.entry(department.trim().to_string())
.or_insert_with(Vec::new)
.push(name.trim().to_string());
}
"d" => {
println!(
"Which department would you like to see?"
);
let mut x = String::new();
io::stdin()
.read_line(&mut x)
.expect("failed to read line");
println!("These people work in {:?}: {:?}", &x.trim().to_string(), directory.get(&x.trim().to_string()));
}
"a" => {
println!(
"These are all the people in our company {:?}.",
names
);
}
"q" => break,
_ => {
println!("you typed {}", yn);
}
}
}