A fun pattern: `if 'label: { …; break 'label true; …; false } { … }`

51 points chris-morgan

I just wanted to share this code that I wrote maybe two or three years ago, which I regretfully discarded today. It’s a menace, but I hold that it’s actually pretty readable, and doing definitely-better is surprisingly difficult. I mean, you can be boring and let mut reinstate = false; and reinstate = true; break; and if reinstate, but where’s the fun in that? When you decide you don’t like just reinstate = true; break;, you quickly go to let reinstate = 'reinstate { …; false };, and then why bother with binding it to a name when it’s already labelled? Yeah, I can see why I wrote it that way. And it definitely still amuses me.

pub fn undefine_style(&mut self, style_name: &str) -> Result<(), RemoveStyleError> {
    // Be optimistic and remove it.
    let Some((style_name, removing_style)) = self.styles.remove_entry(style_name) else {
        return Err(RemoveStyleError::NameNotDefined);
    };
    // Y’know, I’m just going to leave this menace here, because it amuses me.
    if 'reinstate: {
        for style in self.styles.values() {
            if let Some(SpeakAs::Style(speak_style)) = &style.speak_as {
                if *speak_style == removing_style {
                    break 'reinstate true;
                }
            }
            if let Some(FormatAs::Style(format_style)) = &style.format_as {
                if *format_style == removing_style {
                    break 'reinstate true;
                }
            }
            if let System::Extends { style: extended_style } = &style.system {
                if *extended_style == removing_style {
                    break 'reinstate true;
                }
            }
        }
        false
    } {
        // Aww. Put it back.
        self.styles.insert(style_name, removing_style);
        return Err(RemoveStyleError::StyleStillInUse);
    }
    Ok(())
}

^(Is this awful enough that I should have applied the “seeking help & advice” flair?)