如何将参数化枚举从泛型类型映射到另一个类型? [英] How to map a parametrized enum from a generic type to another?

查看:40
本文介绍了如何将参数化枚举从泛型类型映射到另一个类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像 MyEnum 这样的类型,如果不是每个变体都被参数化,我如何映射它?

If I have a type like MyEnum<T>, how can I map it in cases where not every variant is parameterized?

例如,我想从 MyEnum 转换为 MyEnum:

For example, I'd like to convert from MyEnum<u32> to MyEnum<String>:

enum MyEnum<T> {
    B,
    C,
    D(T),
}

fn trans(a: MyEnum<u32>) -> MyEnum<String> {
    match a {
        MyEnum::D(i) => MyEnum::D(i.to_string()),
        other_cases => other_cases,
    }
}

fn main() {}

这失败了:

error[E0308]: match arms have incompatible types
  --> src/main.rs:8:9
   |
8  |         match a {
   |         ^ expected struct `std::string::String`, found u32
   |
   = note: expected type `MyEnum<std::string::String>`
   = note:    found type `MyEnum<u32>`
note: match arm with an incompatible type
  --> src/main.rs:10:28
   |
10 |             other_cases => other_cases,
   |                            ^^^^^^^^^^^

代替 other_cases =>other_cases 行,我试过了,也没有成功:

Instead of the other_cases => other_cases line, I tried this, also without success:

other_cases => {
    let o: MyEnum<String> = other_cases;
    o
}

推荐答案

macro_rules! partial_enum {
    ($name: ident, $some: ident, $($none: ident),+) => {
        #[derive(Debug)]
        enum $name<T> {
            $some(T),
            $($none),+
        }
        impl<T> $name<T> {
            fn convert<U>(self) -> Result<$name<U>, T> {
                match self {
                    $name::$some(x) => Err(x),
                    $($name::$none => Ok($name::$none)),+
                }
            }
        }
    }
}
partial_enum!(MyEnum, D, B, C);
fn trans(a: MyEnum<u32>) -> MyEnum<String> {
    let a_split: Result<MyEnum<String>, u32> = a.convert();
    match a_split {
        Ok(is_none) => is_none,
        Err(not_none) => MyEnum::D(not_none.to_string()),
    }
}
fn main() {
    println!("{:?}", trans(MyEnum::D(13)));
}

这篇关于如何将参数化枚举从泛型类型映射到另一个类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆