美文网首页
rust 解析命令行参数

rust 解析命令行参数

作者: 球果假水晶蓝 | 来源:发表于2023-01-07 23:30 被阅读0次

rust有专门的clap crate解析命令行参数,但是这里我尝试自己解析参数,可以更加方便控制细节。

use std::env;
use colored::Colorize;
// https://stackoverflow.com/questions/15619320/how-can-i-access-command-line-parameters-in-rust 参考资料
fn help() {
    println!("
usage: Commamd [options]
Options:
   {:<10}  111 
   {:<10}  111
   {:<10}  111
   {:<10}  111
   {:<10}  111
   {:<10}  111",
    format!("-w INT").blue(),
    format!("-f INT").green(),
    format!("-D FLOAT").yellow(),
    format!("-N INT1").cyan(),
    format!("-r INT").yellow(),
    format!("-z INT").yellow());
}
fn main() {
    let mut _config;
    let mut size;
    let args:Vec<String> = env::args().collect();
    if args.len() == 1{
        help();
    }
    let mut args = args.iter().skip(1);
    while let Some(arg) = args.next() {
        match &arg[..] {
            "-h" | "--help" => help(),
            "-v" | "--version" => {
                println!("Verbose mode is not supported yet.");
            }
            "-c" | "--config" => {
                if let Some(arg_config) = args.next() {
                    _config = arg_config;
                } else {
                    panic!("No value specified for parameter --config.");
                }
            }
            "-s" | "--size" => {
                if let Some(arg_size) = args.next() {
                    size = arg_size
                        .parse::<usize>()
                        .expect("Size argument expects an integer value.");
                } else {
                    panic!("No value specified for parameter size.");
                }
            }
            _ => {
                if arg.starts_with('-') {
                    println!("Unkown argument {}", arg);
                } else {
                    println!("Unkown positional argument {}", arg);
                }
            }
        }
    }
}

效果如下


image.png

相关文章

网友评论

      本文标题:rust 解析命令行参数

      本文链接:https://www.haomeiwen.com/subject/ypnycdtx.html