As a Rust beginner working on one of the first problems on Exercism/Rust (https://exercism.org/tracks/rust/exercises/assembly-line)
I would like to know if it is possible to constrain integer input to a range at compile-time
to be able to have a clean set of match expression cases.
Below is my current implementation of production_rate_per_hour:
pub fn production_rate_per_hour(mut speed: u8) -> f64 {
speed = cmp::max(speed, 10);
let cars_per_hour: u8 = 221;
match speed {
0 => 0.0,
1 ..= 4 => (speed * cars_per_hour) as f64,
5 ..= 8 => (speed * cars_per_hour) as f64 * 0.9,
9 | 10 => (speed * cars_per_hour) as f64 * 0.77
}
}
I am trying to write a method that accepts a single mutable u8 argument named speed that I then constrain to the range 0..=10 as follows:
speed = cmp::max(speed, 10);
I then want to match speed on all possible cases, i.e. 0..=10.
But since this is a run-time check, the compiler does not see this and tells me to also match integer value 11 and higher:
Compiling assembly-line v0.1.0 (/Users/michahell/Exercism/rust/assembly-line)
error[E0004]: non-exhaustive patterns: `11_u8..=u8::MAX` not covered
--> src/lib.rs:12:11
|
12 | match speed {
| ^^^^^ pattern `11_u8..=u8::MAX` not covered
|
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
= note: the matched value is of type `u8`
I can of course solve this by adding the following case:
// notify
_ => println!("11 or higher")
// or crash
_ => panic!("you've crashed the assembly line!");
// or do something like this:
_ => (cmp::max(speed, 10) * cars_per_hour) as f64 * 0.77;
However, I would like to know if it is possible to constrain the input range at compile-time, and having a "clean" match expression.
Is this possible, if so, how?
_ => (10 * cars_per_hour) as f64 * 0.77;_ => unreachable!(); that is exactly what it is designed for, and it will even hint to the optimizer that the codepath is unreachable. However, i this case I think a better solution would be matching 0 through 9, then_ => handle_like_10.