I'm working my way through the Rust Book:
Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in the 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.
use std::collections::HashMap;
#[derive(Debug)]
enum Command {
Add(String, String),
List,
Unknown
}
fn command_filter(input: String) -> Command {
let mut command_string = input.split_whitespace();
match command_string.next() {
Some("Add") => {
match (command_string.next(), command_string.last()){
(Some(name), Some(dept)) => Command::Add(name.to_string(), dept.to_string()),
_ => Command::Unknown
}
},
Some("List") => Command::List,
_ => Command::Unknown
}
}
fn process_command(command: Command, employee_map: &mut HashMap<String, String>) {
match command {
Command::Add(name, dept) => {
employee_map.insert(name, dept);
()
},
Command::List => {
for (name, dept) in employee_map {
println!("Name: {} Dept: {}", name, dept);
};
},
Command::Unknown => println!("Unknown command!"),
};
}
fn main() {
let mut employee: HashMap<String, String> = HashMap::new();
let command = command_filter(String::from("Add John to Eng"));
process_command(command, &mut employee);
let command = command_filter(String::from("Add Devon to Bio"));
process_command(command, &mut employee);
let command = command_filter(String::from("List"));
process_command(command, &mut employee);
}
As with most devs starting to learn Rust I am finding difficulty with borrowing. I do not come from a C/C++ background and so I'm also finding pointers versus actual object a little tricky too.
Some specific thoughts:
- I am suspicious that match statements inside match statements is not good practice.
- The
Command::Add
branch inprocess_command
feels a little hacky with the()
return. Edit: After thinking more about this problem, I think if I wrapped the branch responses inOk()
then I could return aResult
from that function.
Do you have any feedback?