我有以下功能,其中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
的特征。 关于rust - Rust impl特性作为函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64413750/