Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-exhaustive patterns - Rust match expressions

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?

like image 838
fresh Avatar asked Sep 16 '19 18:09

fresh


People also ask

Does Rust have pattern matching?

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.

What is exhaustive pattern matching?

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.

How does Rust pattern matching work?

Pattern matching in Rust works by checking if a place in memory matches a certain pattern. Patterns can be : literal values. variable names.

What matches with Rust?

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.


1 Answers

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

like image 116
user2722968 Avatar answered Nov 15 '22 10:11

user2722968