What is the Rust equivalent to a try-catch statement?

前端 未结 3 876
情话喂你
情话喂你 2020-12-30 00:19

Is it possible to handle multiple different errors at once instead of individually in Rust without using additional functions? In short: what is the Rust eq

3条回答
  •  温柔的废话
    2020-12-30 01:07

    Results in Rust can be chained using and_then. So you can do this:

    if let Err(e) = do_step_1().and_then(do_step_2).and_then(do_step_3) {
        println!("Failed to perform necessary steps");
    }
    

    or if you want a more compact syntax, you can do it with a macro:

    macro_rules! attempt { // `try` is a reserved keyword
       (@recurse ($a:expr) { } catch ($e:ident) $b:block) => {
          if let Err ($e) = $a $b
       };
       (@recurse ($a:expr) { $e:expr; $($tail:tt)* } $($handler:tt)*) => {
          attempt!{@recurse ($a.and_then (|_| $e)) { $($tail)* } $($handler)*}
       };
       ({ $e:expr; $($tail:tt)* } $($handler:tt)*) => {
          attempt!{@recurse ($e) { $($tail)* } $($handler)* }
       };
    }
    
    attempt!{{
       do_step1();
       do_step2();
       do_step3();
    } catch (e) {
       println!("Failed to perform necessary steps: {}", e);
    }}
    

    playground

提交回复
热议问题