0

I would like to do this:

fn foo(bar: Option<...>) -> ... {
    if let None = bar { // bar is None. No need to go any further
        return ...
    }

    /* Do some complex calculation assuming bar is Some(...) */
}

This kind of approach is fine in untyped languages and even some typed ones like TypeScript and (if memory serves me right) Swift but it won't do for Rust.

What is the idiomatic way to do this that works for return types other than Option and Result? I could do:

if let Some(...) = bar {
    /* complex calculation */
} else {
    return ...
}

It seems akin to a lot of unreadable nested if-else clauses with a lot of indentation in the long run.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Emma
  • 294
  • 1
  • 4
  • 11
  • I believe your question is answered by the answers of [Is there a non-messy way to chain the results of functions that return Option values?](https://stackoverflow.com/q/31172451/155423) and [How do you unwrap a Result on Ok or return from the function on Err?](https://stackoverflow.com/q/51344951/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jan 10 '19 at 00:50
  • https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator – Stargateur Jan 10 '19 at 00:51
  • @Stargateur What you linked to says: "_The ? Operator Can Only Be Used in Functions That Return Result"_. Perhaps i was unclear but my -> ... signature refers to any arbitrary type. – Emma Jan 10 '19 at 01:06
  • I linked to [an answer that applies to any type](https://stackoverflow.com/q/51344951/155423) (yes, it says "Result" in the title, but read the answers). What's insufficient with that answer? – Shepmaster Jan 10 '19 at 01:08
  • 1
    @Shepmaster oh s**t only looked ad the first link then got all busy defending myself. The second link does indeed seam to answer my question – Emma Jan 10 '19 at 01:09
  • Do you feel like this can be marked as a duplicate then? – Shepmaster Jan 10 '19 at 01:10
  • @Shepmaster yeah sure, go ahead. – Emma Jan 10 '19 at 01:13
  • @Hugobastas Rust is *comparatively* new. The [top 200 questions](https://data.stackexchange.com/stackoverflow/query/960749/questions-with-most-views) have between 57K and 6K views. – Shepmaster Jan 10 '19 at 01:21
  • @Shepmaster Yeah, kinda unescesary comment on my part. – Emma Jan 10 '19 at 01:25
  • @Hugobastas oh nevermind, [example of how I will do it](https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=e16a896c1a435af4d4fda5b93c73d085) – Stargateur Jan 10 '19 at 03:13

0 Answers0