-1

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.

stimulate
  • 1,199
  • 1
  • 11
  • 30

1 Answers1

1

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,
    }
}
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • Not intending to overoptimize, just interested if this is less efficient or harder to optimize because of the function call instead of an inline pattern. it does require and extra match statement and introduces a boolean value and a function call. – stimulate Jan 01 '19 at 19:06
  • 2
    @stimulate: Well, first of all, yes it will be slower in Debug. In Release, it will depend whether the guard is inlined or not; with inlining there should be no performance difference... operative word being "should" since optimizers can be finicky. – Matthieu M. Jan 01 '19 at 19:55