Review of "hr manager" :) (chapter 8.3, 3rd exercise)

⚓ rust    📅 2025-05-25    👤 surdeus    👁️ 3      

surdeus

Warning

This post was published 35 days ago. The information described in this article may have changed.

Here I am with another terribly boring exercise, any thoughts on this?
Although I am moderately satisfied with the results, anything that at this stage can be done better?
By that I mean, using the concepts illustrated in the book up until this chapter.
EDIT: I have already renamed the unused variable as suggested.

use std::collections::hash_map::Entry;
use std::{collections::HashMap, io};

fn add(personnel: &mut HashMap<String, Vec<String>>, dept: &str, person: &str) {
    let dept_employees = personnel.entry(dept.to_string());

    match dept_employees {
        Entry::Vacant(entry) => {
            entry.insert(vec![person.to_string()]);
        }
        Entry::Occupied(mut entry) => {
            let people = entry.get_mut();
            if !people.contains(&person.to_string()) {
                people.push(person.to_string());
            }
        }
    }
}

fn list(personnel: &HashMap<String, Vec<String>>, dept: Option<&str>) {
    match dept {
        Some(dept) => {
            if let Some(dept_employees) = personnel.get(dept) {
                for employee in dept_employees {
                    println!("- {}", employee);
                }
            } else {
                println!("No such department.");
            }
        }
        None => {
            for (dept, people) in personnel.iter() {
                println!("Department: {}", dept);
                for person in people {
                    println!("  - {}", person);
                }
            }
        }
    }
}

fn handle_command(input: &str, personnel: &mut HashMap<String, Vec<String>>) {
    let mut parts = input.split_whitespace();

    // Step 1: get the command
    let command = match parts.next() {
        Some(cmd) => cmd,
        None => {
            println!("No command given.");
            return;
        }
    };

    // Step 2: match command and pull arguments accordingly
    match command {
        "add" => {
            let person = match parts.next() {
                Some(name) => name,
                None => {
                    println!("Missing name for 'add'.");
                    return;
                }
            };

            let to_keyword = parts.next();

            let dept = match parts.next() {
                Some(dept) => dept,
                None => {
                    println!("Missing department for 'add'.");
                    return;
                }
            };

            println!("Adding {} to department {}", person, dept);

            add(personnel, dept, person);
        }

        "list" => {
            let dept = parts.next();

            match dept {
                Some(dept) => println!("Listing personnel in department: {}", dept),
                None => println!("Listing all departments"),
            }

            list(personnel, dept);
        }

        _ => println!("Unknown command: {}", command),
    }
}

fn main() {
    let mut personnel: HashMap<String, Vec<String>> = HashMap::new();
    println!("Usage: ");
    println!("adding: add Name to Dept");
    println!("listing: list Dept, list for all Dept");
    println!("quit: empty line");
    loop {
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("Failed to read line");

        let input = input.trim();
        if input.is_empty() {
            break;
        };

        handle_command(input, &mut personnel);
    }
}

(Playground)

Output:

Usage: 
adding: add Name to Dept
listing: list Dept, list for all Dept
quit: empty line
Missing department for 'add'.
Missing department for 'add'.
Adding sara to department sales
Adding john to department devel
Adding peter to department devel
Listing personnel in department: sale
No such department.
Listing personnel in department: sales
- sara
Listing personnel in department: devel
- john
- peter
Listing all departments
Department: devel
  - john
  - peter
Department: sales
  - sara

Errors:

   Compiling playground v0.0.1 (/playground)
warning: unused variable: `to_keyword`
  --> src/main.rs:65:17
   |
65 |             let to_keyword = parts.next();
   |                 ^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_to_keyword`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: `playground` (bin "playground") generated 1 warning
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.74s
     Running `target/debug/playground`

1 post - 1 participant

Read full topic

🏷️ rust_feed