Rust: exercise of employees and names As I'm learning Rust using the second edition of the Rust book I solved the following exercise:


  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.


I could find this solution: Rust exercise department employee management (which did not receive a lot of feedback).

Do you have any feedback on my implementation? The code works, but I can imagine that some refactoring would be good. It already took me a lot of trial and error to get this working :-)

Suggestions welcome!

use std::io;
use std::collections::HashMap;


fn main() {
    let mut employees:HashMap&lt;String, Vec&lt;String&gt;&gt; = HashMap::new();
    println!("Start adding employees or type 'Done' when finished!");
    loop {
        let mut input = String::new();
        io::stdin().read_line(&amp;mut input).expect("error: unable to read user input");
        let parsed_input = dissect_input(input.clone());
        match parsed_input {
            Ok(v) =&gt; {
                let (dept, name) = v;
                employees.entry(dept.to_string())
                    .or_insert_with(Vec::new)
                    .push(name)
            }
            Err(e) =&gt; {
                if e == "End" {
                    println!("Processed all input, good!\n\n");
                    break;
                } else {
                    println!("Input error!");
                    continue;
                }
            }
        }
    }
    println!("Type the name of a department to get its employees.");
    println!("Type 'All' to get all employees by department.");
    println!("Type 'Quit' to quit.");
    loop {
        let mut command = String::new();
        io::stdin().read_line(&amp;mut command).expect("error: unable to read user input");
        match command.trim() {
            "Quit" =&gt; break,
            "All" =&gt; {
                for (dept, names) in &amp;employees {
                    let mut names = names.clone();
                    names.sort();
                    for name in names {
                        println!("{}: {}", dept, name);
                    }
                }
            }
            _ =&gt; {
                match employees.get(&amp;command.trim().to_string()) {
                    Some(names) =&gt; {
                        for name in names { println!("{}: {}", command.trim().to_string(), name); }
                    }
                    None =&gt; println!("I don't recognize that!")
                    }
                }
            }
        }
    println!("Have a nice day!");
    }


fn dissect_input(s: String) -&gt; Result&lt;(String, String), String&gt; {
    match s.trim().as_ref() {
        "Done" =&gt; Err("End".to_string()),
        _ =&gt; {
            let words: Vec&lt;&amp;str&gt; = s.split_whitespace().collect();
            if words.len() != 4 {
                Err("PEBCAK".to_string())
            } else {
            Ok((words[3].to_string(), words[1].to_string())) // “Add Sally to Engineering”
            }
        }
    }

}

// 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.
```
To start, I have some general tips. Run your code through rustfmt to get consistent formatting and make code easier to read. Run your code through clippy to get tips on common mistakes (clippy had nothing to say about your code, nice!)

One overall thing I'd suggest is to not be afraid to use a custom type in a case like this. Instead of returning a Result&lt;(String, String), String&gt; where the Err has multiple meanings based on value, just go ahead and make an Enum for your commands. I'll show you this in my final example, along with merging the two command sections (which the exercise is kinda fuzzy on whether it cares which way you do it).

Onto specific things:

You can get an iterator over lines of stdin by .lock().lines(), which can make this simpler, but that's a matter of preference over using read_line. If you are going to use read_line, you might as well reuse your input buffer, since that's the whole point of it taking a buffer as a parameter instead of just returning a String. That way you aren't reallocating each time. 

let mut stdin = io::stdin()
let mut input = String::new();
loop {
    input.clear();
    stdin.read_line(&amp;mut input).unwrap();
    // ...
}


dissect_input should take a &amp;str instead of a String, since you only need to view it.

Down in the listing part, you do &amp;command.trim().to_string(), which is unneeded in a few ways. .to_string() takes you from a &amp;str to a String, and then the &amp; brings you right back to a &amp;str, so you could just do command.trim(). Also, you can just bind in the match you already have, like dept =&gt; employees.get(dept)

Overall, this is a really good first attempt! It can be hard to first wrap your head around the things that make rust different, like lifetimes and slices, but just getting things working is a great step.

Here's how I might choose to do this exercise.

use std::collections::HashMap;
use std::io;

// required trait for .lines()
use std::io::BufRead;

fn main() {
    let mut employees: HashMap&lt;String, Vec&lt;String&gt;&gt; = HashMap::new();
    let stdin = io::stdin();
    println!("Type 'Add &lt;name&gt; to &lt;department&gt;' to add an employee");
    println!("Type 'List &lt;department&gt;' to list the employees of a department");
    println!("Type 'All' to list all employees by department");
    println!("Type 'Quit' to quit");
    for line in stdin.lock().lines() {
        let input = line.expect("error: unable to read user input");
        match Command::from_input(&amp;input) {
            // or_default is just a convenience, does the same as or_insert_with(Vec::default)
            Some(Command::Add { dept, name }) =&gt; employees.entry(dept).or_default().push(name),
            Some(Command::List(dept)) =&gt; match employees.get(&amp;dept) {
                Some(names) =&gt; {
                    for name in names {
                        println!("{}: {}", dept, name);
                    }
                }
                None =&gt; println!("I don't recognize that department!"),
            },
            Some(Command::All) =&gt; {
                for (dept, names) in &amp;employees {
                    let mut names = names.clone();
                    names.sort();
                    for name in names {
                        println!("{}: {}", dept, name);
                    }
                }
            }
            Some(Command::Quit) =&gt; break,
            // consider using eprintln, which prints to stderr
            None =&gt; println!("Input error!"),
        }
    }
    println!("Have a nice day!");
}

enum Command {
    // Using named fields instead of Add(String, String) because dept and name
    // are the same type and could get mixed up.
    Add { dept: String, name: String },
    List(String),
    All,
    Quit,
}

impl Command {
    fn from_input(s: &amp;str) -&gt; Option&lt;Self&gt; {
        let words: Vec&lt;&amp;str&gt; = s.trim().split_whitespace().collect();
        // "Slice destructuring / slice pattern matching" for more info
        match words.as_slice() {
            ["All"] =&gt; Some(Command::All),
            ["Quit"] =&gt; Some(Command::Quit),
            ["List", dept] =&gt; Some(Command::List(dept.to_string())),
            ["Add", name, "to", dept] =&gt; Some(Command::Add {
                dept: dept.to_string(),
                name: name.to_string(),
            }),
            _ =&gt; None,
        }
    }
}