Help in rustlings exercise quiz1.rs

Need help in fixing the compilation errors encountered while executing
rustlings\exercises\quizzes\quiz1

as per exercise statement i have modified the function

// TODO: Write a function that calculates the price of an order of apples given
// the quantity bought.

fn calculate_price_of_apples(qty : i32) -> i32 {
match qty {
qty if (qty > 40) => qty * 1,
qty if (qty <= 40) => qty * 2,
}
}

--------Compilation Error--------------
error[E0004]: non-exhaustive patterns: i32::MIN..=i32::MAX not covered
--> exercises/quizzes/quiz1.rs:14:13
|
14 | match qty {
| ^^^ pattern i32::MIN..=i32::MAX not covered
|
= note: the matched value is of type i32
= note: match arms with guards don't count towards exhaustivity
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
16 ~ qty if (qty <= 40) => qty * 2,
17 ~ i32::MIN..=i32::MAX => todo!(),
|

For more information about this error, try rustc --explain E0004.
error: could not compile exercises (bin "quiz1") due to 1 previous error

Help/advise needed to find my wrongdoing here.

First, a minor "forum etiquette" thing: putting your code and compiler output in ``` marks (one on an empty line before the code + compiler output, one after) makes it more readable:

// TODO: Write a function that calculates the price of an order of apples given
// the quantity bought.

fn calculate_price_of_apples(qty : i32) -> i32 {
    match qty {
        qty if (qty > 40) => qty * 1,
        qty if (qty <= 40) => qty * 2,
    }
}

--------Compilation Error--------------

error[E0004]: non-exhaustive patterns: `i32::MIN..=i32::MAX` not covered
  --> src/lib.rs:14:11
   |
14 |     match qty {
   |           ^^^ pattern `i32::MIN..=i32::MAX` not covered
   |
   = note: the matched value is of type `i32`
   = note: match arms with guards don't count towards exhaustivity
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
   |
16 ~         qty if (qty <= 40) => qty * 2,
17 ~         i32::MIN..=i32::MAX => todo!(),
   |

For more information about this error, try `rustc --explain E0004`.

The compiler is complaining because it can't see that your match covers all possible values of qty. As the note says, it ignores arms with guards, and thus it's not confident that you're covering everything.

There's lots of ways round this: you could use something other than match, you could take the suggestion and add an arm that unconditionally covers everything, or you could rewrite to remove the guards by changing the pattern from qty to something like a range pattern (e.g. ..=40 for minimum up to or equal to 40).

1 Like

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.