簡體   English   中英

rust clap 解析 ipv4Addr

[英]rust clap parse ipv4Addr

我想使用 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 似乎實現了提供FromStrfrom_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`.

我的問題是:

  • 為什么沒有使用FromStr提供的方法呢?
  • 我怎樣才能修復程序來做我想做的事?

你想要的是默認使用的(因為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,
}

操場

否則,您需要按照示例使用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,

}

操場

Ipv4Addr實現FromStr而不是From<&str> ,它是From trait with &str作為參數。 如果您想使用FromStr ,請指定parse(try_from_str)或省略它,因為它是默認值

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"),
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM