What is a unit variant


#1

Hi everyone,
I’m trying to understand how to use the sdl2 rust library (my question is not directly related with sdl2), but I have a hard time understanding the event queue set up.
Basically I have a loop iterating over every events in the queue, and I want to match the Quit Event.

for event in event_pump.poll_iter() {
	match event {
		Some(sdl2::event::Event::Quit) => running = false,
		_ => {},
	}
}

The sdl documentation says that poll_iter() calls poll_event() for every event, and poll_event return an Option< event::Event>. So event should be an Option< event::Event>. But I get mismatched types, because it looks like event is a variant of event::Event…

Then if I remove Some(), I have another error. The compiler says “expected unit struct/variant, found struct variant”. To fix it, I have to add {. .} after sdl2::event::Event::Quit. But I don’t understand the whys at all. First, I was thinking only enum could have variant, but the compiler says struct variant. Second, I do not know what a unit variant is, why the {. .} is “casting” my variant to unit variant, and why do I need unit variant at all :stuck_out_tongue:

Thanks for the help,
++


#2

Event::Quit is a variant that has a named field, timestamp; variants with named fields are called struct variants. A variant with no fields is called a unit variant. A variant with unnamed (ie positional) fields is called a tuple variant.

So when you’re matching against a struct variant, you can say {..} if you don’t care about matching or capturing the field(s) values.