I have a code which should give number 1 or 5 or 10 or 50.
rust compiler says "pattern 4_u8..=u8::MAX not covered"
the code:
use rand::Rng;
fn main() {
let rand_num: u8 = rand::thread_rng().gen_range(0, 4);
println!("{}", rand_num);
let coin: Coin;
match rand_num{
0 => coin = Coin::Penny,
1 => coin = Coin::Nickel,
2 => coin = Coin::Dime,
3 => coin = Coin::Quarter,
}
println!("{}", value_in_cents(coin));
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin{
Coin::Penny => return 1,
Coin::Nickel => return 5,
Coin::Dime => return 10,
Coin::Quarter => return 25,
}
}
i have no idea how can i fix it
>Solution :
Matches in rust need to be exhaustive. In other words they need to cover every possible case.
When you are matching on the enum Coin you are matching every variant in the enum – so it is valid.
But when you are matching on an integer (in this case, a u8) the possible values can be anywhere from 0 to 255. Consider what happens if the number generated passed to match is 9 – rust would attempt to match and find no matching branch. From there coin would be undefined and the rest of the program would be faulty.
Logically we know that the match will always be exhausted, since rand::thread_rng().gen_range(0, 4); will generate a number within that range. But either way the rules applied to match must be followed. In this case, you can add a fallback branch which will cover any remaining case.
match rand_num{
0 => coin = Coin::Penny,
1 => coin = Coin::Nickel,
2 => coin = Coin::Dime,
3 => coin = Coin::Quarter,
_ => panic!("Invalid coin");
}
This would allow your code to compile – but in the case that an invalid number is generated the program would crash.
As an aside, you could simplify this code by assigning the value of the match directly to the coin variable:
let coin = match rand_num{
0 => Coin::Penny,
1 => Coin::Nickel,
2 => Coin::Dime,
3 => Coin::Quarter,
_ => panic!()
}