【问题标题】:ArgMatches' get_one cannot downcast f64ArgMatches 的 get_one 不能向下转换 f64
【发布时间】:2022-07-02 16:11:12
【问题描述】:

我使用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 函数解析与 boolean 或 usize 的情况不同。

【问题讨论】:

  • 提示一下,第一个代码sn -p可以构建成功,但是当你像./binary -m 0一样运行它时,它只会panic
  • 是的。我面临的错误是恐慌。但是,我不知道为什么以及如何解决它。

标签: rust clap


【解决方案1】:

我找到了恐慌发生的原因,以及如何防止恐慌。 发生恐慌是因为 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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多