thwd
thwd

Reputation: 24808

Unwrap enum when all variants are of the same type

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?

Upvotes: 7

Views: 1532

Answers (1)

Peter Hall
Peter Hall

Reputation: 58725

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.

Upvotes: 14

Related Questions