在我的一个 Rust 项目中,我有一个多级枚举层次结构。这是一个简化版本(游乐场链接):
enum Child {
ChildA,
ChildB,
}
enum Parent {
ParentA(Child),
ParentB,
}
enum GrandParent {
GrandParentA(Parent),
GrandParentB,
}
Run Code Online (Sandbox Code Playgroud)
为了方便起见,我在每个级别与其之上的级别之间实现了转换器:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
如果我想从 a 转换Child为 aParent我现在可以做
let c: Child = Child::ChildA;
let p: Parent = c.into();
Run Code Online (Sandbox Code Playgroud)
但如果我想从 a 转换Child为 a 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
Run Code Online (Sandbox Code Playgroud)
我尝试使用涡轮鱼指定类型,但这也不起作用:
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
Run Code Online (Sandbox Code Playgroud)
将这些调用链接到的正确方法是什么into()?
let c: Child = Child::ChildA;
let gp: GrandParent = Into::<Parent>::into(c).into();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
925 次 |
| 最近记录: |