我可以使用附加值扩充枚举吗? [英] Can I extend an enum with additional values?

查看:192
本文介绍了我可以使用附加值扩充枚举吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个具有一组值的枚举,有没有办法创建一个具有相同变体的第二个枚举呢?

If I have an enum with a set of values, is there a way I could create a second enum with the same variants plus some more?

// From this
enum Base {
    Alpha,
    Beta(usize),
}

// To this, but without copy & paste
enum Extended {
    Alpha,
    Beta(usize),
    Gamma,
}


推荐答案

一个枚举不能被直接扩展,但你使用与struct相同的组合技巧(即,使用一个struct,一个字段存储'parent'的一个实例。

An enum can't be directly extended, but you use the same composition trick one would use with structs (that is, with a struct, one would have a field storing an instance of the 'parent').

enum Extended {
    Base(Base),
    Gamma
}

如果您想单独处理每个案例,然后使用它像

If you wish to handle each case individually, this is then used like

match some_extended {
    Base(Alpha) => ...,
    Base(Beta(x)) => ...,
    Gamma => ...
}

但您也可以从父母

match some_extended {
    Base(base) => base.do_something(),
    Gamma => ...,
}

这篇关于我可以使用附加值扩充枚举吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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