devela::code::util

Macro iif

Source
macro_rules! iif {
    ($if:expr; $true:expr) => { ... };
    ($if:expr ; $true:expr ; $($false:expr)?) => { ... };
    (let $pat:pat = $if:expr ; $true:expr) => { ... };
    (let $pat:pat = $if:expr ; $true:expr ; $($false:expr)? ) => { ... };
}
Expand description

inline if macro.

A inline alternative for if and if let.

ยงExamples

Replacing if:

// This
let s = iif![1 > 0; true; false];

// Would be equivalent to
let s = if 1 > 0 {
    true
} else {
    false
};

Replacing if let:

let num = Some(123);

// This
iif![let Some(n) = num ; println!("num:{n}") ; { dbg![num]; }];

// Would be equivalent to
if let Some(n) = num {
    println!("num:{n}")
} else {
    dbg![num];
}

Nested:

let mut s = String::new();
let is_premium = Some(true);

// This
iif![let Some(b) = is_premium; iif![b; s += " [premium]"]];

// Would be equivalent to
if let Some(b) = is_premium {
    if b {
        s += " [premium]";
    }
}