Can I avoid `_` in comparison with the gen_range pattern?

If I want to matchget the result rand::thread_rng().get_range(1, 3), I need to add a value _, even if I know that there are only two possible values:

match rand::thread_rng().gen_range(1, 3) {
    1 => println!("1"),
    2 => println!("2"),
    _ => panic!("never happens")
};

A case is _useless, but required.

I understand that the compiler cannot guess that it gen_range(1, 3)can only return 1 or 2, but is there a way to avoid adding this useless string _ => panic!("never happens")with matching patterns (perhaps with some hint of the compiler)? Or do I need to replace the last value ( 2) with _?

+4
source share
1 answer

, , gen_range(1, 3) 1 2

. gen_range i32 , i32 .

_ => panic!("never happens")

, unreachable! , panic!:

match rand::thread_rng().gen_range(1, 3) {
    1 => println!("1"),
    2 => println!("2"),
    _ => unreachable!(),
};

(2) _?

, "", , , :

match rand::thread_rng().gen_range(1, 100) {
    1 => println!("1"),
    _ => println!("2"), // oops!
};

, , , , , . , .

"" enum { One, Two },

, , match . .

, 1.1, - #[derive(Rand)] ... , , , .

1 2:

if rand::thread_rng().gen() {
    println!("1")
} else {
    println!("2")
}
+6

Source: https://habr.com/ru/post/1677354/


All Articles