How to avoid pyramid of if let

Hi, I'm building a web server and In the main function, I have a bunch of test that looks like this:

let settings = ...
if let Err(...
} else if let Ok(...

  let database = ...
  if let Err(...
  } else if Ok(...

    let routes = ...
    if let Err(...
    } else if Ok(...

      ... and so on and so forth

During my research to avoid writing this, I found 2497-if-let-chains - The Rust RFC Book that seems not ready yet.

Is there an elegant solution that do not produce nodejs pyramid code?

If you have Results, the conventional way of handling them is to bubble them up using the postfix ? operator.


You can try using a macro like if_chain - Rust

I am pretty convinced that what @moechofe is looking for is the question mark operator, and not the if_chain crate.


I tried it, but AFAIK it drops the Err()

What about the different types of error that can be returned by each lines of codes?

You can map_err to convert external errors to your domain error model, or implement the From trait for them.

Yes, map_err allow to change the type of Err() but what about the Ok(), I also need to chain them.

Then use or or or_else if you want to do flow control with results

You can "chain" the success results like any other Rust values. For example

let settings = get_settings().map_err(|_| MyErr::SettingsErr)?;
let database = Database::connect(&settings)?;
let routes = database.get_routes()?;

If you can post a more complete example, we might be able to give more helpful advice.

let...else is another upcoming feature that will help add flexibility, for cases where you need to run different code at each error point.


That looks good. I will try.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.