rust clap 解析 ipv4Addr

jon*_*dev 5 rust clap

我想使用 clap 派生 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();
}
Run Code Online (Sandbox Code Playgroud)

我的尝试给出了以下错误,即使 Ipv4Addr 似乎实现了FromStr它提供的from_str

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`.
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • 为什么没有使用提供的方法FromStr
  • 我怎样才能修复程序来做我想做的事?

Net*_*ave 7

您想要的是默认使用的内容(因为Ipv4AddrImplements 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,
}
Run Code Online (Sandbox Code Playgroud)

操场

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,

}
Run Code Online (Sandbox Code Playgroud)

操场