Libove Blog

Personal Blog about anything - mostly programming, cooking and random thoughts

I'm missing the vocabulary for googling this.

Is there a better way to write this? I want to filter a vector of enums to elements that match one specific pattern.

.filter(|r| match r.kind {
    RoomKind::BedRoom(_) => true,
    _ => false
})

#rust #dev





Interactions

Reply from Vasile Rotaru:

@h4kor Being a beginner I also do not know, but this the kind of question for which an LLM can hallucinate if not a correct answer, than at least a helpful one.

I'd try Claude.


(Original Post)

Reply from Glyn Wolf :verified_gay::

@h4kor That’s the correct way to do it. You could make it a little shorter using the convenience macro « matches! » (std::matches) which does the work of the match statement for you in the background.


(Original Post)

Reply from Bryan:

@h4kor

```
.filter(|r| matches!(r, RoomKind::BedRoom(_)))
```


(Original Post)

Reply from Manuel Landesfeind:

@h4kor not sure if this would be idiomatic but I would probably go with something like:

.filter(|r| if let RoomKind::BedRoom(_) = r.kind { true } else { false })

https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html


(Original Post)

Reply from chebra:

@h4kor https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html recommends `if let` for avoiding awkward matches, but not sure how much "better" it is in this case:

```
.filter(|r| if let RoomKind::BedRoom(_) = r.kind { true } else { false })
```


(Original Post)

Reply from Vorbis ✨:

@h4kor looks like you're looking for the matches! macro.

https://docs.rs/matches/latest/matches/macro.matches.html


(Original Post)

Reply from Greg Donald:

@h4kor How about matches! ?

.filter(|r| matches!(r.kind, RoomKind::BedRoom(_)))

https://doc.rust-lang.org/std/macro.matches.html


(Original Post)

Reply from Nicolas Mouart 🇪🇺:

@h4kor https://doc.rust-lang.org/book/ch06-00-enums.html ?


(Original Post)

Reply from Soso:

@h4kor using the matches! macro?

https://doc.rust-lang.org/stable/std/macro.matches.html


(Original Post)

Reply from Denis N.:

@h4kor It looks good to me, but I'm following to see if there is another way.


(Original Post)

Reposted by Programming Feed