#Working with enum

6 messages · Page 1 of 1 (latest)

gloomy stag
#

I'm wondering if it's better to use an tagged-enum or to use struct. Since a lot of operators (eg: increment) depend on just the value, I figure using the pattern-matching for tagged-enum will be more bothersome compared to struct where we can opt-into match expr as and when needed

enum RangeEnd {
    Bounded(u32),
    Unbounded(u32),
}
// vs
struct RangeEnd {
    value: u32,
    bounded: bool,
}

Please note: my understanding of match expr and rust idioms is surface-level 😅

wintry anvil
#

the downside of the struct is that code can easily ignore the variant when it shouldn't

rigid frost
# gloomy stag I'm wondering if it's better to use an tagged-enum or to use struct. Since a lot...

I feel like you'd care about the variant anytime you access the value (since presumably your logic is different, e.g. for indexing), so the enum would prevent you from forgetting to check self.bounded.

If there are situations where you really don't care, you can make it easier with an accessor method like this:

impl RangeEnd {
    fn to_value(self) -> u32 {
        match self {
            Self::Bounded(v) | Self::Unbounded(v) => v,
        }
    }
}

An explicit method call is more effort than just accessing a field, so you'll think about whether you really want that every time you do it

wintry anvil
#

you can pattern match like this:

fn increment(&mut self) {
    let (Self::Bounded(b) | Self::Unbounded(b)) = self;
    *b += 1;
}
#

in terms of in-memory representation, the enum and the struct will be identical in practice

gloomy stag
#

I'll try the accessor method, because I'm using the A|B too any times for my liking. Reading and writing doesn't flow that well for me when I have to do that frequently