【问题标题】:rust clap parse ipv4Addrrust clap 解析 ipv4Addr
【发布时间】:2022-12-20 10:56:13
【问题描述】:

我想使用 clap derive API 来解析 Ipv4Addr

#![allow(unused)]
use clap; // 3.1.6
use clap::Parser;
use std::net::Ipv4Addr;

#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
    
    #[clap(short, long, parse(from_str))]
    ip_dst: Ipv4Addr,

}

fn main() {
    let args = Args::parse();
}

即使 Ipv4Addr 似乎实现了提供 from_strFromStr,我的尝试还是出现了以下错误

error[E0277]: the trait bound `Ipv4Addr: From<&str>` is not satisfied
  --> src/main.rs:10:31
   |
10 |     #[clap(short, long, parse(from_str))]
   |                               ^^^^^^^^ the trait `From<&str>` is not implemented for `Ipv4Addr`
   |
   = help: the following implementations were found:
             <Ipv4Addr as From<[u8; 4]>>
             <Ipv4Addr as From<u32>>

For more information about this error, try `rustc --explain E0277`.

我的问题是:

  • 为什么没有使用FromStr提供的方法?
  • 如何修复程序以执行我想要的操作?

【问题讨论】:

    标签: rust clap


    【解决方案1】:

    你想要的是默认使用的(因为Ipv4Addr实现了FromStr),没有指定任何parse选项:

    use clap; // 3.1.6
    use clap::Parser;
    use std::net::Ipv4Addr;
    
    #[derive(Parser, Debug)]
    #[clap(author, version, about, long_about = None)]
    struct Args {
        #[clap(short, long)]
        ip_dst: Ipv4Addr,
    }
    

    Playground

    否则,您需要按照示例使用try_from_str

    #![allow(unused)]
    use clap; // 3.1.6
    use clap::Parser;
    use std::net::Ipv4Addr;
    
    #[derive(Parser, Debug)]
    #[clap(author, version, about, long_about = None)]
    struct Args {
        
        #[clap(short, long, parse(try_from_str))]
        ip_dst: Ipv4Addr,
    
    }
    

    Playground

    【讨论】:

      【解决方案2】:

      Ipv4Addr 实现了 FromStr 但没有实现 From&lt;&amp;str&gt;,它是 From trait 以 &amp;str 作为参数。如果要使用 FromStr,请指定 parse(try_from_str) 或自 it's the default 起省略它。

      【讨论】:

        【解决方案3】:

        Clap v4 更新

        use clap::{arg, value_parser, Command}; // Clap v4
        use std::net::Ipv4Addr;
        
        fn main() {
            let matches = Command::new("clap-test")
                .arg(
                    arg!(--ip <VALUE>)
                        .default_value("127.0.0.1")
                        .value_parser(value_parser!(Ipv4Addr)),
                )
                .get_matches();
        
            println!(
                "IP {:?}",
                matches.get_one::<Ipv4Addr>("ip").expect("required"),
            );
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-10-20
          • 2021-04-20
          • 2021-07-12
          • 1970-01-01
          • 2018-08-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多