![](/img/trans.png)
[英]How to use `Fn` trait with return type of `impl trait` in Rust?
[英]Rust impl Trait as function return type
我有以下函数,其中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
作为返回类型意味着“此函数将返回实现此 trait 的单个类型”,而您试图返回实现该 trait 的多个类型。 这对编译器来说很难,因为它需要知道返回的类型有多大,并且不同的类型有不同的大小。
一些选项:
Box
始终具有相同的大小enum
,将返回值包装在enum
,并为enum
实现特征。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.