Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I chain multiple calls to `into()`?

Tags:

rust

In one of my Rust projects, I have a multi-level hierarchy of enums. Here's a simplified version (playground link):

enum Child {
    ChildA,
    ChildB,
}

enum Parent {
    ParentA(Child),
    ParentB,
}

enum GrandParent {
    GrandParentA(Parent),
    GrandParentB,
}

For convenience, I have implemented converters between each level and the level above it:

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)
    }
}

If I want to convert from a Child to a Parent I can now do

let c: Child = Child::ChildA;
let p: Parent = c.into();

But if I want to convert from a Child to a Grandparent, I can't seem to chain multiple calls to 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

I tried specifying the type using a turbofish, but that doesn't work either:

    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

What's the correct way to chain these calls to into()?

like image 486
Greg Owen Avatar asked Oct 23 '25 14:10

Greg Owen


1 Answers

let c: Child = Child::ChildA;
let gp: GrandParent = Into::<Parent>::into(c).into();
like image 124
ephemient Avatar answered Oct 25 '25 14:10

ephemient



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!