Search code examples
rustpattern-matchingaliases

Can I name a pattern in Rust?


I am using winit to create a window and get input from the user through the window. The window creates variants of the enum Event and passes it to a "callback function" (I am not sure how accurate this is) for processing.

I am using match statements to decide what to do with the event:

fn process_event(event: winit::Event) -> winit::ControlFlow /*potentially break EventsLoop and exit*/ {
    match event {
        winit::Event::WindowEvent { // match against close request event
            event: winit::WindowEvent::CloseRequested,
            ..
        } => winit::ControlFlow::Break,
        _ => winit::ControlFlow::Continue
    }
}

However, this is getting very noisy quickly. I am currently splitting all the different cases up into functions, so that I can make this code a bit more expressive, but in the end, the patterns remain this verbose. It would be very nice if I could give a pattern to match against a name, I mean something like this:

pattern quitEvent =
    winit::Event::WindowEvent {
        event: winit::WindowEvent::CloseRequested,
        ..
    };

fn process_event(event: winit::Event) -> winit::ControlFlow {
    match event {
        quitEvent => winit::ControlFlow::Break,
        _ => winit::ControlFlow::Continue
    }
}

Is this possible? Even better would be if we could alias a combination of patterns aswell, in an "or" manner.


Solution

  • There are no aliases for patterns in Rust (1.31).

    There are guard clauses, though, and they can invoke functions:

    match event {
        n if is_quit_event(n) => winit::ControlFlow::Break,
        _ => winit::ControlFlow::Continue,
    }
    

    Would therefore be possible, and of course within the function you can do any computation.

    Here, the function would be:

    fn is_quit_event(event: winit::Event) -> bool {
        match event {
            winit::Event::WindowEvent { // match against close request event
                event: winit::WindowEvent::CloseRequested,
                ..
            } => true,
            _ => false,
        }
    }