我有以下功能,其中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
works?
不幸的是,这并不完全是这样impl Trait
does. impl Trait
作为返回类型意味着“此函数将返回实现此特征的单个类型”,而您试图返回实现此特征的多个类型。这对于编译器来说很困难,因为它需要知道返回的类型有多大,并且不同的类型有不同的大小。
一些选项:
- 将返回值装箱,因为
Box
始终具有相同的尺寸
- 定义一个
enum
每个返回类型都有一个变体,将您的返回值包装在enum
,并实现特征enum
.
- Use https://crates.io/crates/auto_enums它会自动创建 2 中描述的枚举。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)