简体   繁体   English

从if语句中返回值时出现“类型不匹配”错误

[英]Returning a value from within an if statement has a “mismatched types” error

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. 在下面的函数中,我匹配&str的第一个完整字符,如果它是*-_以及返回的是那些字符,那么我想用_臂检查该字符是否为空格,否则返回'a'

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`

You don't want a return here, you're not trying to return from the function. 您不希望在这里返回,也不想在函数中返回。 Just use the 'a' as an expression. 只需使用'a'作为表达式。 You also need the space char as an else branch, not standing on its own. 您还需要将空格字符作为else分支,而不是独立存在。

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

Why the else is required 为什么需要else

if is an expression, and it has to evaluate to some value. if是一个表达式,它必须求值。 That value needs a definite type; 该值需要一个确定的类型。 it can't sometimes be a char and sometimes something else. 有时不能是char ,有时不能是其他char If you were to just do this: 如果您只是这样做:

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

What would the if expression evaluate to in case the test fails? if测试失败, if表达式会得出什么结果? Instead of just evaluating to some arbitrary char value, the language simply requires an else branch. 语言不只是求值一个任意的char值,而是只需要一个else分支。 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 . 如果您不想将if用作表达式,而只是将其用于副作用,则可以省略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. 在那种情况下,它仍然是一个表达式,但是它的值是() (与测试是否通过无关),并且您需要以一个语句结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM