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).