程序参数
标准库
可以使用 std::env::args
来访问命令行参数,它返回一个迭代器,为每个参数产生一个 String
。
use std::env; fn main() { let args: Vec<String> = env::args().collect(); // The first argument is the path that was used to call the program. println!("My path is {}.", args[0]); // The rest of the arguments are the passed command line parameters. // Call the program like this: // $ ./args arg1 arg2 println!("I got {:?} arguments: {:?}.", args.len() - 1, &args[1..]); }
$ ./args 1 2 3
My path is ./args.
I got 3 arguments: ["1", "2", "3"].
包
此外,还有许多包可以在创建命令行应用程序时提供额外的功能。 其中一个比较流行的命令行参数包是 clap
。