在我的 Rust 项目中,我有一个多层级的枚举层次结构。这是一个简化版(playground link):
如果我想从一个
enum Child {
ChildA,
ChildB,
}
enum Parent {
ParentA(Child),
ParentB,
}
enum GrandParent {
GrandParentA(Parent),
GrandParentB,
}
为了方便起见,我已经实现了每个级别与其上一级之间的转换器:
impl From<Child> for Parent {
fn from(c: Child) -> Self {
Parent::ParentA(c)
}
}
impl From<Parent> for GrandParent {
fn from(p: Parent) -> Self {
GrandParent::GrandParentA(p)
}
}
如果我想从一个
Child
转换成一个Parent
,现在可以这样做。let c: Child = Child::ChildA;
let p: Parent = c.into();
但是,如果我想从一个Child
转换为一个Grandparent
,似乎无法将多个调用链接到into()
中:
let c: Child = Child::ChildA;
let gp: GrandParent = c.into().into();
error[E0282]: type annotations needed
--> src/main.rs:30:29
|
30 | let gp: GrandParent = c.into().into();
| --^^^^--
| | |
| | cannot infer type for type parameter `T` declared on the trait `Into`
| this method call resolves to `T`
|
= note: type must be known at this point
我尝试使用Turbofish指定类型,但这也不起作用:
let c = Child::ChildA;
let gp: GrandParent = c.into::<Parent>().into();
error[E0107]: wrong number of type arguments: expected 0, found 1
--> src/main.rs:31:36
|
31 | let gp: GrandParent = c.into::<Parent>().into();
| ^^^^^^ unexpected type argument
如何正确地链式调用 into()
函数?
impl AsRef<Child> for Parent
和impl AsRef<Parent> for Child
有何看法? - MeetTitanChild
结构体(这种转换通常是在最后一次使用Child
结构体时进行),但AsRef
也是一个有价值的工具。 - Greg Owen