使用Clap解析命令行参数实现Rust版cat命令的代码完善咨询
Clap解析命令行参数实现Rust版cat命令的代码完善咨询
我正在尝试用Rust实现类似Unix系统中cat命令的功能,目前已经用clap库搭好了基础的命令行参数解析框架,但还没完成-n(打印所有行号)和-b(仅为非空行打印行号)这两个参数的解析部分,下面是我已经写好的代码,想请各位帮忙完善剩下的参数配置,同时也想请教下如何处理这两个参数同时出现的优先级问题(通常-b会覆盖-n):
use clap::{value_parser, Arg}; use std::error::Error; type MyResult<T> = Result<T, Box<dyn Error>>; pub fn run(config: Config) -> MyResult<()> { dbg!(config); Ok(()) } #[derive(Debug)] pub struct Config { files: Vec<String>, // -n print the line number number_lines: bool, // -b print the line number only for nonblank lines number_nonblank_lines: bool, } pub fn get_args() -> MyResult<Config> { let matches = clap::Command::new("catr") .author("Liu yifan, 0219lyf@gmail.com") .version("0.1.0") .about("Rust cat") .arg( Arg::new("files") .value_name("FILE") .help("Input file(s)") .num_args(1..) .default_value("-") .value_delimiter(' '), ) .arg( // 这里需要补充-n和-b参数的配置逻辑 ); // 这里还需要从matches中提取参数值并构造Config实例 Ok(Config { files: matches.get_many::<String>("files").unwrap().cloned().collect(), number_lines: false, // 待完善 number_nonblank_lines: false, // 待完善 }) }
备注:内容来源于stack exchange,提问作者刘一凡
相关产品推荐
相关产品推荐

