Yor*_*ian 3 reference slice rust
我正在尝试学习 Rust 编程语言(目前主要使用 python)。Rust 网站提到的任务之一是构建系统,将员工和部门添加到充当“商店”的 HashMap 中。
在代码中,我尝试将其拆分为单独的函数,该函数解析用户输入并检查它是否是列出部门或添加员工的请求。接下来,我想要特定的函数来处理这些操作。
假设输入的形式为:
Add employee to department
Run Code Online (Sandbox Code Playgroud)
然后我希望初始解析函数检测到该操作是“添加”,我想将其传递给处理添加的函数“add”。
我已将字符串按空格分割为字符串向量。是否可以将该向量的切片 (["employee", "to", "department"]) 传递给函数 add?看来我只能通过完整的参考了。
我的代码:
fn main() {
// this isnt working yet
let mut user_input = String::new();
let mut employee_db: HashMap<String,String> = HashMap::new();
get_input(&mut user_input);
delegate_input(&user_input[..], &mut employee_db);
user_input = String::new();
}
fn get_input(input: &mut String) {
println!("Which action do you want to perform?");
io::stdin().read_line(input).expect("Failed to read input");
}
fn delegate_input(input: &str, storage: &mut HashMap<String,String>) {
// Method is responsible for putting other methods into action
// Expected input:
// "Add user to department"
// "List" (list departments)
// "List department" (list members of department)
// "Delete user from department"
// "" show API
let input_parts: Vec<&str> = input.split(' ').collect();
if input_parts.len() < 1 && input_parts.len() > 4 {
panic!("Incorrect number of arguments")
} else {
println!("actie: {}", input_parts[0]);
match input_parts[0].as_ref() {
"Add" => add(&input_parts),
"List" => list(&input_parts),
"Delete" => delete(&input_parts),
"" => help(),
_ => println!("Incorrect input given"),
}
}
}
fn add(parts: &Vec<&str>) {
println!("Adding {} to {}", parts[1], parts[3]);
}
Run Code Online (Sandbox Code Playgroud)
你可以传一片。
将您的添加签名更改为此:
fn add(parts: &[&str]) {
Run Code Online (Sandbox Code Playgroud)
然后你可以用以下方式调用它:
"Add" => add(&input_parts[1..3]),
Run Code Online (Sandbox Code Playgroud)