macro_rules! try_block {
{ $($token:tt)* } => { ... };
}Expand description
Macro for the recieving end of a ? operation.
Right now, type inference is quite finicky so you usually have to declare a concrete type somewhere.
// Note: this fails without explicitly specifying the error type.
let y: Result<_, std::num::ParseIntError> = try_block! {
"1".parse::<i32>()? + "2".parse::<i32>()?
};If you know that a block will have a specific type, it may aid type inference to use
the macros try_opt, try_res, and try_cf.
§Alternative
The only other way to emulate try blocks is with closures, which is very ugly.
§Before:
ⓘ
let result: Result<T, E> = (|| {
let a = do_one(x)?;
let b = do_two(a)?;
Ok(b)
})();§After:
let result: Result<T, E> = try_block! {
let a = do_one(x)?;
let b = do_two(a)?;
b
};