Max value of an enum

I have the following code:

#[derive(Debug)]
enum SettlementSize {
    Village,
    Town,
    City,
}

impl Distribution<SettlementSize> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> SettlementSize {
        let res = rng.gen_range(0, 3);
        match res {
            0 => SettlementSize::Village,
            1 => SettlementSize::Town,
            2 => SettlementSize::City,
            _ => panic!("Unknown value!"),
        }
    }
}

If I add a new entry to the SettlementSize, e.g. MegaCity, I wouldn't like to forget to increase the value in rng.gen_range(0, 3); to 4. Is there some way to detect the maximum value in the enum (as cast to a number)? Do I need to maintain a watcher/guard at the end of the enum for that purpose?

Haskell has an Enum trait for just this purpose, and I've been looking for it in Rust, the same as you. Are we both just missing something trivial?

@fosskers I hoped for something similar to Java or Python.

I found the strum crate, which allows me to do: UniqueFeature::iter().count(). I am not sure how to remove the call to iter and just do UniqueFeature::count(). This is a on an enum with struct variants.

maybe you could do:


#[derive(Debug)]
enum SettlementSize {
    Village = 0,
    Town,
    City,
    Other,
    Last,
}

fn get_range() -> usize {
    SettlementSize::Last as usize
}

fn main() {
    let l = get_range();
    println!("l: {:}", l);
}

There's a crate for that!

Adds max_value() to enums.

3 Likes

I tried that, but it only worked for non-struct variants.

Thanks, let me try it out!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.