Yorian
Yorian

Reputation: 2062

Pass slice of vector as argument to function

I'm trying to learn the Rust programming language (currently working mostly in python). One of the assignments that the rust website mentions is building system to add employees and departments to a HashMap that acts as a "store".

In the code I'm trying to split it into separate functions, one which parses the user input and checks whether it is a request to list the departments or to add an employee. Following that I want specific functions to handle the actions.

Say the input is in the form of:

Add employee to department

Then I want the initial parsing functions to detect that the action is "Add" from where I want to pass it to the function "add" which handles the addition.

I've split the String by whitespace into a vector of Strings. Is it possible to pass a slice of that vector (["employee", "to", "department"]) to the function add? It seems like I can only pass the full reference.

My code:

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]);
}

Upvotes: 3

Views: 4030

Answers (1)

michael_bitard
michael_bitard

Reputation: 4212

You can pass a slice.

change your add signature to this:

fn add(parts: &[&str]) {

then you can call it with:

"Add" => add(&input_parts[1..3]),

Upvotes: 6

Related Questions