Does ?-operator have 'local exit'?

  1. I’ve looked at https://stackoverflow.com/questions/42980104/how-to-use-and-catch-in-rust and https://m4rw3r.github.io/rust-questionmark-operator and I am confused on a very simple question: how can we get local exit with ?-operator ?

  2. I want something like

pub fn foo() { // note the lack of a -> Option ...

  let x: Option<...> = { black magic here ...
    ...? ; / I want this ?, on None, to set x to None
  }
}

Is something like the above (or standard trycatch blocks that can catch ?) available in Rust?

This would be possible with try blocks but they have not landed yet. Another way you could do this is by using closures.

(|| {
    // ... your code here
})()

If this is too ugly for you, then you could use this macro

macro_rules! try_block {
    ($($rest:tt)*) => { (|| { $($rest)* })() };
}

try_block! {
    // your code here...
}

playground link

3 Likes

You can test out try{} blocks on nightly: https://doc.rust-lang.org/unstable-book/language-features/try-blocks.html

Experience reports welcome!

1 Like