Consider an enum definition like this:
enum Money {
USD(u32),
EUR(u32),
CHF(u32),
// many more...
}
Note that all enum variants are of type u32
.
fn amount(money: Money) -> u32 {
// ?
}
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,
}
}
}
At least this way you only have to do it once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With