Macro konst::try_rebind

source ·
macro_rules! try_rebind {
    (
        $pattern:tt = $expression:expr $(,)?
    ) => { ... };
}
Expand description

Like the ? operator, but also reassigns variables with the value in the Ok variant.

Note: the Ok variant can only be destructured into a single variable or a tuple.

§Let pattern

You can declare new variables with let patterns like this:

try_rebind!{(let foo, bar) = Ok((10, 20))}
try_rebind!{(let (a, b, c), bar) = Ok(((10, 10, 10), 20))}

foo in here is a new variable initialized with 10 (same for a, b, and c), while bar is a pre-existing variable that is assigned 20.

This pattern only works when destructuring tuples.

§Examples

§Parsing

Inside of parse_int_pair, parser always refers to the same variable.

use konst::{
    parsing::{Parser, ParseValueResult},
    try_rebind, unwrap_ctx,
};

const fn parse_int_pair(mut parser: Parser<'_>) -> ParseValueResult<'_, (u64, u64)> {

    // `parser` is reassigned if the `parse_u64` method returns an `Ok`.
    // (this also happens in every other invocation of `try_rebind` in this example)
    try_rebind!{(let aa, parser) = parser.parse_u64()}

    try_rebind!{parser = parser.strip_prefix(',')}

    try_rebind!{(let bb, parser) = parser.parse_u64()}

    Ok(((aa, bb), parser))
}

const PAIR: (u64, u64) = {
    let parser = Parser::new("100,200");
    unwrap_ctx!(parse_int_pair(parser)).0
};

assert_eq!(PAIR, (100, 200));