Match binding with if inside

                ch = match stream.peek() {
                    None => {
                        '\0'
                    },

                    Some(valid) => {
                        if !valid.is_ascii_digit() {
                            '\0';
                        }

                        stream.next().unwrap()
                    }
                };

I am trying to use match binding, but something is not working as it should. It looks like "if" is being ignored, I used the debugger and found that "is_ascii_digit ()" is being executed but regardless of what the function returns the body of "if" is ignored. What could be happening?

I believe you meant:

Some(valid) => {
  if !valid_is_ascii_digit() {
    // Note: no semicolon
    '\0'
  } else {
    // Note: within an else block
    stream.next().unwrap()
  }
}

As for what's actually happening: when !valid.is_ascii_digit() is true, you hit the expression '\0' but immediately throw it away (;), after which you continue pase the if block and execute stream.next().unwrap() and "return" this out of the match to assign to ch. If it is not true, you skip the if body which does nothing, then still continue on to stream.next().unwrap().

Another, related example:

// Say `f` and `g` return `String`s
let x = if (some_boolean) {
  f()
} else {
  g()
};
// `x` is a `String`

let x = if (some_boolean) {
  f(); // Note the new semicolon
} else {
  g(); // Note the new semicolon
};
// Now `x == ()` -- the semicolon "swallowed" any return from `f`/`g`
2 Likes

I'll try not to forget how to use the semicolon, thanks

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.