Macro konst::try_rebind [−][src]
This is supported on crate feature
parsing_no_proc
only.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.
Mapping errors
You can optionally map the returned error like this:
try_rebind!{foo = bar(), map_err = |e| convert_this_error(e)}
or
try_rebind!{foo = bar(), map_err = convert_this_error}
The convert_this_error
function is expected to return the error type that
the current function returns.
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_u8(b',')} try_rebind!{(let bb, parser) = parser.parse_u64()} Ok(((aa, bb), parser)) } const PAIR: (u64, u64) = { let parser = Parser::from_str("100,200"); unwrap_ctx!(parse_int_pair(parser)).0 }; assert_eq!(PAIR, (100, 200));