将向量的切片作为参数传递给函数

3
我是一名python程序员,现在正在学习Rust编程语言。Rust官网提到的一个任务是构建一个系统,将员工和部门添加到充当“存储”角色的HashMap中。
在代码中,我试图将其拆分为单独的函数,其中一个函数解析用户输入并检查它是否是列出部门或添加员工的请求。接下来,我希望有特定的函数来处理这些操作。
假设输入的形式为:
Add employee to department

我希望最初的解析函数能够检测到操作是“添加”,然后将其传递给处理添加的函数“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]);
}
1个回答

6
你可以传递一个slice
将您的添加签名更改为以下内容:
fn add(parts: &[&str]) {

然后您可以使用以下方式调用它:
"Add" => add(&input_parts[1..3]),


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接