Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Reinvent match Desugaring

In Turn ? into .unwrap() behind a feature we showed that with the consume-question feature enabled, adding ! at the end of the method allows replacing ?.

We can therefore replace ? with a match. A fun example worth documenting.

First, enable consume-question:

cargo add hooq --features consume-question

Define the match expression in hooq.toml (the original is $expr). The flavor is named my_match since match is reserved:

[my_match]
method = """
match $expr {
    Ok(val) => val,
    Err(err) => return Err(From::from(err)),
}!
"""

Write main.rs as usual (add #[allow(clippy::question_mark)] to avoid lints):

use hooq::hooq;

fn failable<T>(val: T) -> Result<T, String> {
    Ok(val)
}

#[hooq(my_match)]
#[allow(clippy::question_mark)]
fn main() -> Result<(), String> {
    let _ = failable(42)?;

    Ok(())
}

Expansion shows a match as intended:

#![feature(prelude_import)]
#[macro_use]
extern crate std;
#[prelude_import]
use std::prelude::rust_2024::*;
use hooq::hooq;
fn failable<T>(val: T) -> Result<T, String> {
    Ok(val)
}
#[allow(clippy::question_mark)]
fn main() -> Result<(), String> {
    let _ = match failable(42) {
        Ok(val) => val,
        Err(err) => return Err(From::from(err)),
    };
    Ok(())
}