Problems with iterators in for loop


#1

I am making a new program and I have a function specifically for parsing command line arguments given to it. I loop over a Vec<String> reference and for each loop, I use a match expression to find a -o argument. If it’s found, I store the output name in a variable named program_output_name by calling args.next(). But I get the error no method namednextfound for type 'std::vec::Vec<std::string::String>' in the current scope. How do I get the next iteration of args to get the output name?

Code:

fn parse_command_line_args(args: Vec<String>, compile_args_global: &mut CompilerArgs) {
    // This is used to keep track of the number of input files given
    let mut total_input_files = 0;
    for arg in &args {
        match arg.as_str() {
            "-o" => {
                let program_ouput_name = args.next();
                // do something with program_ouput_name
            }

            _ => ()
        }
    }
}

#2

Use while let loop instead.


#3

I tried this implementation:

fn parse_command_line_args(mut args: Vec<String>, compile_args_global: &mut CompilerArgs) {
    // This is used to keep track of the number of input files given
    let mut input_files: Vec<String> = Vec::new();
    while let Some(arg) = args.pop() {
        match arg.as_str() {
            "-o" => {
                let program_output_name = args.pop().unwrap_or(String::from("-1"));
                println!("{}", program_output_name);
            }
            _ => ()
        }
    }
}

But it prints the path to the executable.


#4

Vec::pop() removes the last item in the vector, so with that you’d be processing in reverse.

Try something like:

    let mut iter = args.into_iter();
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "-o" => {
                let program_output_name = iter.next().unwrap_or(String::from("-1"));
                println!("{}", program_output_name);
            }
            _ => ()
        }
    }

#5

Thank you! This is exactly what I was looking for!


#6

If this is more than just a learning exercise, consider using a crate like clap (+ structopt possibly) for a CLI.