【问题标题】:The trait `std::convert::From<cli::Opts>` is not implemented特征 `std::convert::From<cli::Opts>` 未实现
【发布时间】:2020-11-23 15:25:34
【问题描述】:

我尝试使用 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` 

代码如下:

ma​​in.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);
}

cli.rs:

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"]}

我做错了什么?

【问题讨论】:

    标签: rust clap


    【解决方案1】:

    您已将mod cli 添加到lib.rsmain.rs

    他们从彼此的角度来看是不同的。

    Rust modules confusion when there is main.rs and lib.rs 可能有助于理解这一点。

    这就是错误所说的。对std::convert::From&lt;minimal_example::cli::Opts&gt; 满意,但对std::convert::From&lt;cli::Opts&gt; 不满意。

    一个简单的修复:

    ma​​in.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);
    }
    

    现在为Config 实现std::convert::From&lt;cli::Opts&gt;

    您实际上希望如何放置所有这些取决于您的包架构。

    【讨论】:

    • 感谢您指出问题!我已经在 cli.rs 模块中实现了 From 特征,现在它可以工作了!在我看来,在main.rs 中逻辑地实现它并不是一个好主意。但是,您对这个问题的提示是正确的!
    • 从逻辑上讲,在 main.rs 中不声明 mod cli 可能更正确,而是通过 pub mod clipub use cli::Opts 从 lib.rs 导出它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 2023-02-01
    • 2022-12-07
    • 2022-06-16
    • 2015-10-08
    • 1970-01-01
    相关资源
    最近更新 更多