4 ms·
let x = match x { Some(x) => x, None => return None, } This implies your function returns an `Option`, and that `x` is an `Option` too. In which
by glandium 9y ago
let x = match x {
Some(x) => x,
None => return None,
}
This implies your function returns an `Option`, and that `x` is an `Option` too. In which case you can just do
let x = x?;
- always_good 9y agoWell, you may be short-circuiting for any reason, from any signature. For example, look a Swift's guard statements. It even narrows the type down-scope after you short-circuit. If you borrow in the `match {expr}`, Rust still thinks it matters when you're trying to short-circuit in the `None` branch and will complain about the borrowed lifetime. Though this is something #![feature(nll)] fixes. You can implement std::ops::Try for a custom data structure, but that doesn't help you in any of the cases where you just want to do some day-to-day short-circuiting without inventing your own data structure. I shouldn't have used Option, though. It was a bad example.
- yjh0502 9y agoI used it frequently when mixing `Result` with `Future`. For example, fn do_something() -> Box<Future<Item=(), Error=Error>> { let val = match do_result() { Ok(x) => x, Err(e) => return Box::new(err(e.into())), }; // do something with `val` unimplemented!(); }
- curun1r 9y agoIf you want to cut down on lines, this is equivalent: let val = do_result().map_err(|e| Box::new(err(e.into())))?;