This commit is contained in:
Jasper Ras 2026-01-15 09:09:24 +01:00
parent eb9773627e
commit 10b29ad9cb
14 changed files with 164 additions and 0 deletions

63
ch8/ch10/usrmgt.rs Normal file
View file

@ -0,0 +1,63 @@
use std::io;
use std::collections::HashMap;
fn main() {
let mut departments: HashMap<String, Vec<String>> = HashMap::new();
loop {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let words: Vec<&str> = input.split_whitespace().collect();
if words.is_empty() { continue; }
match words[0].to_lowercase().as_str() {
"add" => {
// Format: add [name] [department]
if words.len() >= 3 {
let v = departments.entry(String::from(words[2])).or_insert(Vec::new());
v.push(String::from(words[1]));
}
},
"del" => {
// Format: del [name] [department]
if words.len() >= 3 {
let v = departments.entry(String::from(words[2])).or_insert(Vec::new());
let mut idx: Option<usize> = None;
for (i, who2) in v.into_iter().enumerate() {
if who2 == words[1] {
idx = Some(i);
break;
}
}
match idx {
Some(x) => { v.remove(x); () },
None => (),
};
}
},
"ls" => {
if words.len() == 1 {
println!("{departments:?}");
}
if words.len() >= 2 {
let dpt = String::from(words[1]);
let ppl = departments.entry(dpt.clone()).or_insert(Vec::new());
ppl.sort();
println!("The following people are in the {} department:", dpt);
for pp in ppl {
println!("{pp}");
}
}
},
_ => println!("Unknown command"),
}
println!("");
}
}