Escaping enum match arms


#1

Hey guys,

Having some problems getting an enum destructured into a generic struct:

struct Z<T> {
  v: Box<T>,
}

impl<T> Z<T> {
  fn new(input: Box<T>) -> Z<T> {
    Z { v: input }
  }
}

enum A {
  B(Box<bool>),
  C(Box<u32>),
}

// A -> Z<T>
fn convert<T>(input: A) -> Z<T> {
  match input {
    A::B(x) => Z::new(x),
    A::C(y) => Z::new(y),
  }
}

Which gives back the errors:

error[E0308]: mismatched types
   --> src/test.rs:102:23
    |
102 |     A::B(x) => Z::new(x),
    |                       ^ expected type parameter, found bool
    |
    = note: expected type `std::boxed::Box<T>`
               found type `std::boxed::Box<bool>`

error[E0308]: mismatched types
   --> src/test.rs:103:23
    |
103 |     A::C(y) => Z::new(y),
    |                       ^ expected type parameter, found u32
    |
    = note: expected type `std::boxed::Box<T>`
               found type `std::boxed::Box<u32>`

Where I expected that T be applicable here to both u32 and bool. What is the standard way of converting from an enum like this into a generic struct?


#2

fn convert<T>(input: A) -> Z<T> gives the caller the power to choose T, and your implementation would have to create a Z<T> for any type T.

You’re wanting either a Z<bool> or Z<u32> at runtime depending on the parameter, and there’s not really a way to write that beyond an enum like you already have.


#3

The standard way to do this is a put a bunch of methods on your enum (into_bool, into_u32, etc.). There’s no fast and easy way of doing it unless you are willing to use a macro.


#4

Looks like I will use into_* methods or a macro in that case, thanks for the input.