How to handle error for a block of code?

For language like Python, a try/catch can works on a block of code, to save coding for each possible place of error.
For language like Haskell, I can compose functoins together to get the “final status”.

But for Rust, I learnt the try!/? way to work on one Result. But how can I do it to a few, for example, a sequence of IO operations.

There are several approaches.

  1. Combinators:
File::open(fname)
  .and_then(|f| f.read_all(&mut vec))
  .and_then(...)?;
  1. Extract the sequence into its own function returning Result and work with its result.
  2. Variant of the above, but with a closure that you immediatelly run.
(|| -> Result<(), std::io::Error> {
  let f = File::open(fname)?;
  Ok(())
})()?

The try { .. } block should eventually do something similar to the 3. in much friendlier way, but AFAIK it is not yet stabilized.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.