Is there a way to shorten this `match`?

Sorry for posting, but I can't come up with keywords to google this, I only get either questions about enum variants, or about (non)exhaustive matches.

This looks really ugly:

if !do_skip && match name { b"nd" | b"tag" | b"member" => true, _ => false } {

Is there a way to check if name is in a set of several [u8]'s? The best I tried was to put it into a function, but it is used only in one place.

I thought of using HashSet instead (my_hashset.contains(name)), but it seems much more expensive and equally verbose.

You can always put it into a function even if it is used in only one place. Functions denote an abstraction or something that you want to do - even if you are doing it only once.
One fairly simple way would be to:

fn is_name_valid(name: &[u8]) -> bool {
    const names: [&'static [u8]; 3] = [b"nd", b"tag", b"member"];

The matches! macro is a shorthand for those kind of match. For example in you case you can change it to:

if !do_skip && matches!(name, b"nd" | b"tag" | b"member") {

Interesting, I actually forgot how simple arrays are. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.