rust - Rust impl特性作为函数返回类型

标签 rust

我有以下功能,其中Command是特征

pub fn parse_arguments(matches: ArgMatches) -> Result<impl Command, &'static str>
在函数体内,我想根据参数返回Command的不同实现。
喜欢
match args.subcommand() {
    ("init", Some(args)) => {
        Ok(Init::new(args))
    }
    ("btc", Some(args)) => {
        Ok(ImportBtc::new(args))
    },
    ("grin", Some(args)) => {
        Ok(ImportGrin::new(args))
    },
    _ => Err ("Invalid subcommand supplied")
}
编译将失败,并显示以下错误:
expected struct `commands::cmd_types::Init`, found struct `commands::cmd_types::ImportBtc`
ImportGrin返回行类似。
我是否误解了impl Trait的工作原理?

最佳答案

不幸的是,这不是impl Trait所做的。 impl Trait作为返回类型意味着“此函数将返回实现该特征的单个类型”,而您试图返回实现该特征的多个类型。对于编译器来说这很困难,因为它需要知道返回的类型有多大,并且不同的类型具有不同的大小。
一些选项:

  • 框返回值,因为Box始终具有相同的大小
  • 定义一个enum,每种返回类型都有一个变体,将您的返回值包装在enum中,并实现enum的特征。
  • 使用https://crates.io/crates/auto_enums自动执行2中描述的枚举创建。
  • 关于rust - Rust impl特性作为函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64413750/

    相关文章:

    rust - 将两个整数相除不会在 Rust 中打印为十进制数

    enums - 我如何只匹配枚举的部分而不是所有变体?

    binaryfiles - 用于检查 .rlib 二进制文件的 Rust 库

    websocket - Rouille 中 websocket 的高 CPU 使用率

    unicode - 在 Rust 中模拟 Python 的 `index(separator, start_index)`

    process - 如何在 Rust 中存储进程

    rust - 循环外的Rust不匹配类型错误

    arrays - 是否有一种正确的方法可以在引用一维中转换二维数组

    rust - str 和 string 之间不匹配

    datetime - BadFormat 在使用 Chrono 时将字符串解析为最新