rust - 特质 `std::convert::From<cli::Opts>`未实现

标签 rust clap

我尝试使用clap库创建一个简单的应用程序来解析命令行参数,并将其转换为Config自定义结构。我为我的结构实现了From特征,但是,当我尝试调用from函数时,收到以下错误:

the trait bound `minimal_example::Config: std::convert::From<cli::Opts>` is not satisfied
the following implementations were found:
  <minimal_example::Config as std::convert::From<minimal_example::cli::Opts>>
required by `std::convert::From::from` 
这是代码:
main.rs:
mod cli;

use clap::Clap;
use minimal_example::Config;

fn main() {
    println!("Hello, world!");
    let opts = cli::Opts::parse();
    let config = Config::from(opts);
}
客户:
use clap::{Clap, crate_version};

/// This doc string acts as a help message when the user runs '--help'
/// as do all doc strings on fields
#[derive(Clap)]
#[clap(version = crate_version!(), author = "Yury")]
pub struct Opts {
    /// Simple option
    pub opt: String,
}
lib.rs:
mod cli;

pub struct Config {
    pub opt: String,
}

impl From<cli::Opts> for Config {
    fn from(opts: cli::Opts) -> Self {
        Config {
            opt: opts.opt,
        }
    }
}
cargo.toml:
[package]
name = "minimal_example"
version = "0.1.0"
authors = ["Yury"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clap = {version="3.0.0-beta.2", features=["wrap_help"]}
我究竟做错了什么?

最佳答案

您已将mod cli添加到lib.rsmain.rs中。
从彼此的角度来看,它们是不同的。
Rust modules confusion when there is main.rs and lib.rs
可能有助于理解这一点。
这就是错误的意思。它对std::convert::From<minimal_example::cli::Opts>满意,但对std::convert::From<cli::Opts>不满意。
一个简单的解决方法:
main.rs

mod cli;
use clap::Clap;
use minimal_example::Config;

impl From<cli::Opts> for Config {
    fn from(opts: cli::Opts) -> Self {
        Config {
            opt: opts.opt,
        }
    }
}

fn main() {
    println!("Hello, world!");
    let opts = cli::Opts::parse();
    let config = Config::from(opts);
}
现在为std::convert::From<cli::Opts>实现了Config
您实际如何放置所有这些内容取决于您的程序包体系结构。

关于rust - 特质 `std::convert::From<cli::Opts>`未实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64963625/

相关文章:

rust - 什么是有效字符以及如何在clap.rs参数中转义?

rust - 如何防止最后一个参数需要用 clap 引用?

rust - 如何在升级到 Rust Clap v4 时更改 .multiple

rust - 构建和绑定(bind)旧的 libc 版本

rust - 重构后结构的可见性现在公开;无法将 main 添加到 pub (在 crate::main 中)

rust - 使用尺寸大于屏幕的 newpad 时出现问题

rust - Rust:使用拍手来分析用户输入的字符串,以进行命令行编程

rust - 有没有办法让拍手使用文件中的默认值?

rust - 转换失败时如何选择性地规范化值?