[英]Parsing command line arguments in Rust
I am working on a command line program where I need to parse the cli arguments.我正在开发一个命令行程序,我需要在其中解析 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.我有一个名为ìnto_num_vec()
的 function,它接受一个字符串向量,我应该将它解析为一个新的整数向量。
Code from lib.rs来自 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". function 正在恐慌,我收到自定义恐慌消息“解析错误”。
Code in main.rs main.rs 中的代码
use sort_program::*; use std::env; fn main() { let args: Vec<String> = env::args().collect(); affirm_args(args); }
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); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.