ArgMatches的get_one不能向下投射f64



我使用了clap crate来解析代码中的参数。我的代码关于定义和解析参数的最小结构如下:

use clap::builder::Command;
use clap::{Arg, ArgMatches};
let matches = Command::new("test")
.arg(Arg::new("mass")
.short('m')
.takes_value(true))
.get_matches()
let mass: f64 = *matches.get_one::<f64>("mass").unwrap();

但是我面临一个错误"线程'main'惊慌失措'在定义和访问mass之间的不匹配。无法向下转换为f64,需要向下转换为alloc::string:: string ">

我可以通过使用parse()从String到f64来修复它。

let mass: f64 = *matches.get_one::<String>("mass").unwrap().parse().unwrap();

我想知道为什么只有f64不能被get_one函数解析,这与布尔值或usize的情况不同。

我发现了恐慌发生的原因,以及如何防止恐慌。发生恐慌是因为clap没有自动检测浮点类型参数。我们应该为浮点型或其他自定义类型指定值解析器(或等价的参数类型)(在定义命令时)。

let matches = Command::new("test")
.arg(Arg::new("mass")
.short('m')
.takes_value(true))
.value_parser(clap::value_parser!(f64))
.get_matches()

那么,恐慌就解决了。在上述代码块中,clap::value_parser!(f64)的结果为_AnonymousValueParser(ValueParser::other(f64))

在我的例子中,它只是无法将值解析为所提供的类型(并显示一个不太有用的错误消息)。它就像我试图解析类型&str:

matches.get_one::<&str>("arg");

这会使程序产生恐慌,因为它无法将输入解析为&str。我使用的解决方案是解析为String,然后将转换为&str:

matches.get_one::<String>("arg").map(|s| s.as_str());

最新更新