I have an issue with the following Rust code:
pub fn median(v: &Vec<i32>) -> f32 {
let len = v.len();
match len % 2 {
0 => (v[len / 2 - 1] + v[len / 2]) as f32 / 2 as f32,
1 => v[(len - 1) / 2] as f32,
}
}
This code doesn't compile due to a 'Non exhaustive patterns' error. Why is that? What does the % operator return?
Patterns are a special syntax in Rust for matching against the structure of types, both complex and simple. Using patterns in conjunction with match expressions and other constructs gives you more control over a program's control flow.
Exhaustive matching basically means that the compiler, given that he knows all the possible states, can tell you when you are missing one state in your match.
Pattern matching in Rust works by checking if a place in memory matches a certain pattern. Patterns can be : literal values. variable names.
All natural shades, such as greens and sands look equally great when combined with rust. If you are looking to turn a home into an escape and create an inviting nook for winding down after a long day, then look no further than this warm color scheme.
The compiler is not smart enough to figure out that the result of len % 2
can only ever be 0
or 1
. It demands a match arm for cases where the result is some other value. You can solve this by explicitly saying that those cases are impossible:
match len % 2 {
0 => (v[len / 2 - 1] + v[len / 2]) as f32 / 2 as f32,
1 => v[(len - 1) / 2] as f32,
_ => unreachable!()
}
The _
will match any other value not previously mentioned. The unreachable!()
tells the compiler "this code will never execute", but cause a panic!()
just in case it does in fact execute. That way, the program is correct all the time at practically no cost.
Future versions of the compiler might figure out that the values 2..
or not possible.
The %
is the remainder operator
(not to be cofused with the mod
-operator).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With