Rust 软件包管理使用的是 cargo,对应的站点是 crate.io,在这个站点中,收录了很多实用的 crate。
在 crates 站点中,有一个经常用于命令行工具开发的命令行工具包 —— clap。我们可以在 Rust 项目的依赖声明文件 Cargo.toml 中引入 clap:clap = "2.33.0"。更新后的 toml 文件内容如下:
[package]
name = "cookbook"
version = "0.1.0"
authors = ["suhanyujie <[email protected]>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = "2.33.0"此时运行 cargo build 就会把该依赖下载到你本地并编译。随后,在入口函数处编写示例代码:
pub fn try_with_test_param() {
// app 实例化
let matches = App::new("ver").version("v0.1.0")
.author("suhanyujie<[email protected]>")
.about("just a version output")
.arg(Arg::with_name("testParam")// 参数声明
.short("t")
.long("testParam")
.takes_value(true)
.help("enter a random string")
)
.get_matches();
// 参数处理
if let Some(test_param) = matches.value_of("testParam") {
println!("the test param is :{:?}", test_param);
} else {
println!("the test param is not found");
}
}上面的代码中,通过 App::new("ver") 可以实例化一个命令行 app,名称为 ver,这很好理解,毕竟 Rust 这门语言的表现力还是非常强的。实例化后可以继续链式调用 version 声明该命令行 app 的版本;通过 author 声明好该 app 的作者,除此之外,还有很多的参数,如 bin_name 表示运行时的进程名称;long_about 方法表示更详细的 app 简介。更多的方法可以直接看源码。
如果是自己从零开始写命令行程序,那么你需要处理各种各样的参数,如长参数名、短参数名、帮助信息的显示。但是 clap 已经都帮你封装好了,让你只需要聚焦于程序功能本身,而不必花太久的时间在其他非功能处理上。参数处理是写命令行程序非常重要的一个环节,我们看看 clap 是如何帮助我们处理参数的。
1.实例化 `Arg` 类型
2.将实例化的 `Arg` 放入 `App` 实例的 `arg` 方法中.arg(Arg::with_name("testParam")
.short("t")
.long("testParam")
.takes_value(true)
.help("enter a random string")
)Arg 的 with_name 方法是构造函数,它会返回 Arg 实例,表示一个带有名称的参数。实例化后调用它的 short 方法可以指定它的短参数名。以常用的 help 参数为例 -h 是短参数名,对应的 --help 则是长参数名。调用 long 方法就能指定长参数名:.long("testParam"),用法是 --testParam 12312。如果你需要给你的参数添加帮助信息,以便用户输入错误的参数时提示用户如何输入,可以调用 Arg 的 help 方法,如 .help("enter a random string")。如果不止一个命令行参数,可以指定多个,像这样链式多次调用 arg 函数:
.arg(Arg::with_name("testParam1")
.short("t")
.long("testParam1")
.takes_value(true)
.help("enter a random string")
)
.arg(Arg::with_name("file")
.short("f")
.long("file")
.takes_value(true)
.help("enter a file name")
)在实际接收对应的参数进行处理时,我们只需通过 if let + matches.value_of("param_name") 模式匹配即可:
if let Some(param_name) = matches.value_of("param_name") {
println!("the test param is :{:?}", param_name);
}代码段中,如果你声明了一个参数 param_name,并且通过匹配上了 param_name 后,参数值会存放在 param_name 变量中,此时就能根据你的需要进行逻辑处理。上面的代码中只是将参数进行了打印输出 println!("the test param is :{:?}", param_name);。