0
enum MealTime {
    Breakfast,
    Lunch,
    Dinner,
}

 for n in 1..3 {
        let mealc: MealTime = match n {
            1 => MealTime::Breakfast,
            2 => MealTime::Lunch,
            3 => MealTime::Dinner,
        };

At first I tried doing for meal in MealTime {} but discovered that would not work because rust does not support iterating through enums (at least not by default or without implementing the trait yourself). So then I decided to just use a standard for loop ranged by an integer only to realize that using the iterator to match a variable to one of the enums types causes an error:

error[E0004]: non-exhaustive patterns: i32::MIN..=0_i32 and 4_i32..=i32::MAX not covered.

How is this supposed to be done? I would think that matching for all 3 cases of n being 1, 2, and 3 would work.

Papu
  • 47
  • 7

2 Answers2

4

A replacement for for meal in MealTime {} could be:

for meal in [MealTime::Breakfast, MealTime::Lunch, MealTime::Dinner] {
    // do something with meal
}

For more explanations and solutions, see Is there a way to iterate through the values of an enum?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
2

The problem is that Rust doesn't know that n will only ever be one of 1, 2, or 3, it assumes that n could be any i32. So what to do if n == 5? If you're sure any value other than 1, 2, or 3 is impossible to occur, you can give the compiler a hint with the unreachable! macro, like this:

for n in 1..=3 {
    let mealc: MealTime = match n {
        1 => MealTime::Breakfast,
        2 => MealTime::Lunch,
        3 => MealTime::Dinner,
        _ => unreachable!(),
    };
}

If n ever is something other than 1, 2, or 3 this program will panic. By the way, you will have to write 1..=3 instead of 1..3. 1..3 is the exclusive range, 1..=3 the inclusive range.

isaactfa
  • 5,461
  • 1
  • 10
  • 24