我正在阅读Rust编程语言,并决定在第8章末完成第三项任务。说明如下:
使用散列映射和向量,创建文本界面,允许用户向公司的部门添加员工姓名。例如,“添加萨利到工程”或“添加Amir到销售”。然后让用户按部门检索所有人员或公司所有人员的列表,并按字母顺序排序。
请告诉我我的密码是否有用。
use std::collections::HashMap;
use std::io;
use std::io::Write;
use regex::Regex;
fn main() {
let add_regex = Regex::new(r"^(?i)Add\s(\w(?:\w|\s)*\w?)\sto\s(\w+)$").unwrap();
let list_regex = Regex::new(r"^(?i)List\s(\w+)$").unwrap();
let all_regex = Regex::new(r"^(?i)Show all$").unwrap();
let mut departments: HashMap> = HashMap::new();
loop {
let mut input = String::new();
print!("Enter command: ");
io::stdout().flush();
io::stdin().read_line(&mut input);
input = String::from(input.trim());
let add_match = add_regex.captures(&input);
let list_match = list_regex.captures(&input);
let all_match = all_regex.captures(&input);
if add_match.is_some() {
let unwrapped_match = add_match.unwrap();
let employee = &unwrapped_match[1];
let dpt = &unwrapped_match[2];
match departments.get_mut(dpt) {
Some(v) => {
v.push(String::from(employee));
v.sort();
},
None => {
let emp_list = vec![String::from(employee)];
departments.insert(String::from(dpt), emp_list);
}
}
} else if list_match.is_some() {
let unwrapped_match = list_match.unwrap();
let employees = departments.get(&unwrapped_match[1]);
if !employees.is_some() {
println!("No such department");
continue;
}
println!("Department employees: {}", employees.unwrap().join(", "));
io::stdout().flush();
} else if all_match.is_some() {
for (dpt, employees) in &departments {
println!("{}: {}", dpt, employees.join(", "));
}
} else {
println!("Please enter a valid command");
}
}
}样本输出:
Enter command: add f to ff
Enter command: add b to ff
Enter command: list ff
Department employees: b, f
Enter command: add Darth Vader to ff
Enter command: list ff
Department employees: Darth Vader, b, f
Enter command: add d to zz
Enter command: add 1 to zz
Enter command: show all
ff: Darth Vader, b, f
zz: 1, d发布于 2019-01-27 14:50:48
一目了然:这个函数太长了,嵌套得很深。在我的经验中,三层循环/分支嵌套是任何函数应该拥有的最多的层次;嵌套越多,嵌套的时间就越短。
考虑提取分支和循环体以分离命名函数。
您的代码结构似乎也是“确定要执行的命令”(add / list / etc),然后是“执行上述命令”。我会将其显式化,在一个返回命令类型和参数的单独函数中对输入行进行regexp解析。在您自己的命令类型上分配这将是match的一种自然使用。(也就是说,在现实的CLI中,您可能需要可用的命令才能扩展,所以不要太适应这种模式。我猜你会在这本书后面讲到动态多态性。)
https://codereview.stackexchange.com/questions/212321
复制相似问题