Returning a value from within an if statement has

2020-04-18 05:19发布

问题:

In the function below, I match the first full character of a &str, and if it is a *, -, or _ and if it is those that character is returned, and with the _ arm I want to check if the character is whitespace, and return 'a' otherwise.

fn print_character(text: &str) {
    let character: char = match text.chars().nth(0).unwrap() {
        ch @ '*' | ch @ '-' | ch @ '_' => ch,
        ch @ _ => {
            if !ch.is_whitespace() {
                return 'a';
            }
            ' '
        }
    };

    println!("{}", character);
}

When I run the code I get the error below:

error[E0308]: mismatched types
 --> src/main.rs:6:24
  |
6 |                 return 'a';
  |                        ^^^ expected (), found char
  |
  = note: expected type `()`
             found type `char`

回答1:

You don't want a return here, you're not trying to return from the function. Just use the 'a' as an expression. You also need the space char as an else branch, not standing on its own.

if !ch.is_whitespace() {
    'a'
} else {
    ' '
}

Why the else is required

if is an expression, and it has to evaluate to some value. That value needs a definite type; it can't sometimes be a char and sometimes something else. If you were to just do this:

if !ch.is_whitespace() {
    'a'
}

What would the if expression evaluate to in case the test fails? Instead of just evaluating to some arbitrary char value, the language simply requires an else branch. If you don't want to use the if as an expression, and just use it for its side-effects, then you can leave out the else. In that case, it is still an expression, but its value is () (irrespective of whether the test passed or not), and you need to end it with a statement.



标签: rust