Home > Back-end >  Parsing command line arguments in Rust
Parsing command line arguments in Rust

Time:07-04

I am working on a command line program where I need to parse the cli arguments. My problem is that there is an error when I try to parse elements from a vector of Strings

I have a function called ìnto_num_vec() which takes a vector of Strings and I should parse it into a new vector of integers.

Code from lib.rs

pub fn affirm_args(input: Vec<String>) {
    if input.len() < 2 {
        panic!("To few arguments");
    } else {
        let numbers = into_num_vec(input);
        print_numbers(numbers);
    }
}


fn into_num_vec(input: Vec<String>) -> Vec<i32> {
    let mut collection: Vec<i32> = Vec::new();

    for i in input {
        match i.trim().parse() {
            Ok(n) => collection.push(n),
            Err(_) => panic!("Error parsing")
        }
    }

    collection
 }

 pub fn print_numbers(input: Vec<i32>) {
    for i in input {
         println!("{}", i);
    }
 }

The function is panicking and I'am getting the custom panic msg "Error parsing".

Code in main.rs

use sort_program::*;

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    affirm_args(args); 
}

CodePudding user response:

The first argument to a program traditionally is the executable name. You should skip it:

fn main() {
    let args: Vec<String> = env::args().skip(1).collect();
    affirm_args(args); 
}
  • Related