Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwrap enum when all variants are of the same type

Tags:

enums

rust

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?

like image 877
thwd Avatar asked Mar 19 '19 11:03

thwd


1 Answers

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.

like image 147
Peter Hall Avatar answered Nov 01 '22 09:11

Peter Hall