3

I want to check if the result from a request is having any issue. I categorize it into two: i) server error, ii) something else that is not a success. The third category is, result actually being a success. However, in the third category, I don't want to do anything.

So, my desirable code is:

if res.status().is_server_error() {
        panic!("server error!");
    } else if !(res.status.is_success()){
        panic!("Something else happened. Status: {:?}", res.status());
    } else{
        pass;
    }

I am aware of other ways to achieve this result: using match, ifs instead of if else if. But I wanted to learn what is the corresponding keyword of pass, like we have in Python. My aim is: if result is successful, just move along, if not, there are two ways to handle that panic.

Herohtar
  • 5,347
  • 4
  • 31
  • 41
Aviral Srivastava
  • 4,058
  • 8
  • 29
  • 81
  • 4
    Maybe just leave the else branch out completely? – Péter Leéh Feb 03 '22 at 07:26
  • That is a way, and that is what I mean by "`if`s" in my question. But I want to know about a no-op in Rust, similar to pass, something that would do nothing if an if condition is true. – Aviral Srivastava Feb 03 '22 at 07:27
  • 7
    You can leave an empty block and the program will compile. `pass` in python is required since python is an indent-sensitive language, but Rust is not. – geobreze Feb 03 '22 at 07:30

2 Answers2

13

Behold!

if predicate {
    do_things();
} else {
    // pass
}

Or even better

if predicate {
    do_things();
} // pass

Or as I’ve recently taken to calling it the implicit + pass system

if predicate {
    do_things();
}

In all seriousness there is no pass and no need for a pass in rust. As for why it exists in python, check out this answer

nlta
  • 1,716
  • 1
  • 7
  • 17
12

Python needs pass because it uses indentation-based blocks, so it requires some syntax to "do nothing". For example, this would be a syntax error in a Python program:

# syntax error - function definition cannot be empty
def ignore(_doc):
    # do nothing

count = process_docs(docs, ignore)  # just count the docs

The ignore function has to contain a block, which in turn must contain at least one statement. We could insert a dummy statement like None, but Python provides pass which compiles to nothing and signals the intention (to do nothing) to the human reader.

This is not needed in Rust because Rust uses braces for blocks, so one can always create an empty block simply using {}:

// no error - empty blocks are fine
fn ignore(_doc: &Document) {
    // do nothing
}

let count = process_docs(docs, ignore);  // just count the docs

Of course, in both idiomatic Python and Rust, one would use a closure for something as simple as the above ignore function, but there are still situations where pass and empty blocks are genuinely useful.

user4815162342
  • 141,790
  • 18
  • 296
  • 355