当所有变体都是相同类型时,解开枚举 [英] Unwrap enum when all variants are of the same type

查看:94
本文介绍了当所有变体都是相同类型时,解开枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这样的枚举定义:

enum Money {
    USD(u32),
    EUR(u32),
    CHF(u32),
    // many more...
}

请注意,所有枚举变量的类型均为 u32

Note that all enum variants are of type u32.

fn amount(money: Money) -> u32 {
    // ?
}

我可以一般性地提取包装好的 u32 Money 实例中包含的c $ c>而不在所有情况下都匹配,如果是,如何匹配?

Can I generically extract the wrapped u32 contained in a Money instance without matching on all cases, if yes, how?

推荐答案

不幸的是,没有内置的方法可以做到这一点。通常的方法是创建访问器方法:

There isn't a built-in way to do this, unfortunately. The usual approach is to create an accessor method:

impl Money {
    pub fn amount(&self) -> u32 {
        match *self {
            Money::USD(amount) => amount,
            Money::EUR(amount) => amount,
            Money::CHF(amount) => amount,
        }
    }
}

至少您只需要做一次。

这篇关于当所有变体都是相同类型时,解开枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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