Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an error about non-exhaustive patterns?

I'm writing a chat server using mio (0.5.1), following this tutorial. With it, I have written the following Handler:

const SERVER_TOKEN: Token = Token(0);

impl Handler for WebSocketServer {
    type Timeout = usize;
    type Message = ();

    fn ready(&mut self, event_loop: &mut EventLoop<WebSocketServer>,
             token: Token, events: EventSet)
    {
        match token {
            SERVER_TOKEN => {
                let client_socket = match self.socket.accept() {
                    Err(e) => {
                        println!("Accept error: {}", e);
                        return;
                    },
                    Ok(None) => unreachable!("Accept has returned 'None'"),
                    Ok(Some((sock, addr))) => sock,
                };

                self.token_counter += 1;
                let new_token = Token(self.token_counter);

                self.clients.insert(new_token, client_socket);
                event_loop.register(&self.clients[&new_token],
                                    new_token, EventSet::readable(),
                                    PollOpt::edge() | PollOpt::oneshot()).unwrap();
            }
        }
    }
}

However, in trying to compile it I get an error:

error[E0004]: non-exhaustive patterns: `Token(_)` not covered
  --> src/main.rs:23:15
   |
23 |         match token {
   |               ^^^^^ pattern `Token(_)` not covered

error: aborting due to previous error

Although I understand that this should mean that my match does not cover all possible cases, I do not see how that is true.

Why am I getting this error, and how may I fix it?

like image 592
Bernardo Meurer Avatar asked Dec 08 '16 10:12

Bernardo Meurer


1 Answers

Here SERVER_TOKEN is a constant equal to Token(0), so let's simplify the match:

match token {
    Token(0) => { },
}

While you know that you won't get any other tokens, the compiler doesn't know, and the type allows other values like Token(1). You can add a case to cover the other cases, and just panic. I like to print out what was matched if it ever does happen as a debug aid.

match token {
    SERVER_TOKEN => { },
    x => panic!("Unexpected invalid token {:?}", x),
}

This assumes that Token implements Debug.

like image 167
Chris Emerson Avatar answered Nov 14 '22 10:11

Chris Emerson