Could someone please create `dbg_true!()` and `dbg_some!()`?

I'm using dbg!() conveniently.

I wish there was a dbg_true!() that takes a bool type and prints only when it's true.

I wish there was a dbg_some!() that takes an Option<> type and prints only when it's Some().

Could someone make one?

You can:

#[macro_export]
macro_rules! dbg_true {
    ( $condition:expr, $to_print:expr $(,)? ) => {{
        match $to_print {
            to_print => {
                if $condition {
                    eprintln!("[{}:{}:{}] {} = {:#?}",
                        file!(), line!(), column!(), stringify!($to_print), &to_print);
                }
                to_print
            }
        }
    }}
}

#[macro_export]
macro_rules! dbg_some {
    ( $value:expr $(,)? ) => {
        if let Some(value) = $value {
            eprintln!("[{}:{}:{}] {} = {:#?}",
                    file!(), line!(), column!(), stringify!($value), &value);
            Some(value)
        } else {
            None
        }
    }
}
9 Likes

You can also use #[prelude_import] to make it available all throughout your crate

That seems to be an unstable thing, with no tracking issue even (according to prelude_import - The Rust Unstable Book). So usually irrelevant (or at least should have a giant caveat attached to it).

1 Like

I thought I saw it somewhere in the regular docs but I can't bet my life on that.