Is there a nicer syntax for `if let ... Some(destructred_field) else None`?

I currently have:

self.filter_map(|entry| {
    if let TocEntry::FirstTrackInfo { track, control, .. } = entry
        && control.is_audio()
    {
        Some(*track)
    } else {
        None
    }
})

which, I hope for obvious reasons, I don't really like :ferris_clueless:

Is there a reasonable syntax for this? Or some kind of chainable set of methods?

My solution will be avoid the closure completely by using a chain of filters and maps, but it would still be nice to know if there is a better option for the above closure for the future ...

self.filter(|entry| entry.control().is_audio())
    .filter(|entry| matches!(entry, TocEntry::FirstTrackInfo { .. }))
    .map(TocEntry::track)
    .flatten()
    .next()

I'm not aware of a general way to improve on this sort of filter_map — in particular, there is no language feature which directly turns a pattern match success or failure into Option — but the direction I would look at is whether there are any methods you can add to TocEntry that would make this work better and also better-documented.

For example, what does matching that the entry is a FirstTrackInfo actually do? Does it mean "this is the first track rather than some other track"? If so, then how about adding an is_first() method? Then you could write:

self.filter(|entry| entry.control().is_audio() && entry.is_first())
    .map(TocEntry::track)
    .flatten()
    .next()

This doesn’t only get rid of your complex filter_map, but also may help clarify what the condition you’re actually testing for is.

Unrelatedly, .map().flatten() can always be replaced with .flat_map(), or, if the type being flattened is Option, .filter_map().

To my eye using direct match might be cleaner?

self.filter_map(|entry| {
    match entry {
        TocEntry::FirstTrackInfo {track, control, ..} if control.is_audio() => Some(*track),
        _ => None,
    }
})

Then if your desired condition changes or some additional condition would need to result in Some(value), it's easier to modify than if let?

impl TocEntry {
    fn first_audio_track(&self) -> Option<Track> {
        let Self::FirstTrackInfo { track, control, .. } = self else {
            return None;
        };
        control.is_audio().then(|| *track)
    }
}

// ...

self.filter_map(TocEntry::first_audio_track)

I do think it would help to say which parts of it you don't like. The destruction? The else? The None? The indenting? The …

For example, depending which parts are the answer, there are possibilities like a

self.filter_map(|entry| bikeshed!(
    let TocEntry::FirstTrackInfo { track, control, .. } = entry
        && control.is_audio() => *track
))

(err, or something -- not sure I got the follow sets realistic in the example)

Hmm ... I guess my original statement should have been "for reasons which I can't quite put my finger on, but feel should be obvious". It took me a moment to really think about the answer to this:

  1. Yeah, the formatting is discordant, but that get a touch better when outside a closure and feels more like a warning smell than a problem to me
  2. The mental switch from function chaining (iterator adaptors) to blocks is more discordant. Again, that is context-related, and I have a function-chained alternative for this which I've used
  3. I think the main issue is that "if then some(thing_from_the_if_clause) else none" just feels like a verbose version of something that has a very obvious default else.

Thinking overnight, what I was looking for was a version of this (on nightly) which captures from within the matches! and avoids the and_then.

matches! {entry, TocEntry::FirstTrackInfo { control, .. } if control.is_audio()}
    .then_some(entry)
    .and_then(TocEntry::track);

PS - for a moment, I thought you'd actually put a bikeshed! macro into rustc and were pointing it out :ferris_cat:

Thanks for the tip. I managed to further simplify the final version to

/// Parse the entry detailing the track number of the first audio track, if present
fn find_first_audio_info(self) -> Option<TrackNo> {
    self.filter(|entry| matches!(entry, TocEntry::FirstTrackInfo { .. }))
        .filter(|entry| entry.control().is_audio())
        .find_map(TocEntry::track)
}

For a bit of background

It's in a crate dedicated to handling audio CDs.

The very start of a CD is dedicated to a Table of Contents, with data blocks which are effectively a bag-of-bytes with "well defined fields" that are then re-used for various other things depending on the context and the values of other fields :ferris_melt: (of course!, because real space constraint, 1980's design, ... Technically it's not a wire-protocol but effectively it works like one)

So in this case, for one response format, the usual data format is as per the first row below, but there is also an entry as defined in the second row based on a sentinal "track number"

AdrCtl TNO Point Min Sec Frame ZERO PMin Psec PFrame
bitflags incl Data/Audio 0 TrackNumber 0 0 0 0 Start Mins Start Secs Start Frame
bitflags incl Data/Audio 0 0xA0 0 0 0 0 First Track No 0 0

That felt like something worth abstracting away into an enum, hence the FirstTrackInfo variant, if I'm going to the trouble of creating a nice library.

There are a few of them on crates.io, search for "extract macro". There was a proposal to add one to std (I personally would find it useful) but it wasn’t accepted.

One macro solution that I wrote (not knowing about any others before) is as_variant!. With it, your example can be simplified to:

self.filter_map(as_variant!(
    TocEntry::FirstTrackInfo { track, control }
        if control.id_audio() => *track,
))

There is no problem which cannot be solved by introducing more types. :wink:

When you have something like this:

enum Track {
    FirstTrack { ... },
    DataTrack { ... },
}

A useful pattern (for me) is to define more specific types with some TryFrom impls:

struct FirstTrack { ... }

impl TryFrom<Track> for FirstTrack {
    type Error = SomeErrorType;
    
    fn try_from(track: Track) -> Result<Self, Self::Error> {
        match track {
            Track::FirstTrack { ... } => Ok(FirstTrack { ... }),
            _ => Err(())
        }
    }
}

Using these types, you can (try) convert a more general object to a specific one. Then add some From impls for SomeErrorType and you can use the question-mark-operator, flat_map and so on very easy. This gets rid of many if/else constructs.

Nice touch adding the "as closure" case! I'll keep the crate in mind for the future.

Yeah. The latest changes I made have provided named types for all variants rather than using anonymous structs for the less-common ones.

It took me a moment to consider why I'd preferred getter methods to (Try)From and then noticed that API Guidelines - C-GETTER explains this perfectly, assuming you consider C-CONV-TRAITS equivalent to C-CONV.

The getters work great in matches!().then_some(this).map(THIS::getter) just as From would.