“不匹配的类型:期望的`()`”在使用if表达式时意味着什么?

时间:2014-07-04 19:07:13

标签: rust

我尝试在Rust中实现fizzbuzz并且因为一些神秘错误而失败:

fn main() {
    let mut i = 1;

    while i < 100 {
        println!(
            "{}{}{}",
            if i % 3 == 0 { "Fizz" },
            if i % 5 == 0 { "Buzz" },
            if !(i % 3 == 0 || i % 5 == 0) { i },
        );
        i += 1;
    }
}

错误:

error: mismatched types: expected `()` but found `&'static str` (expected () but found &-ptr)
                 if i % 3 == 0 { "Fizz" },
                               ^~~~~~~~~~
error: mismatched types: expected `()` but found `&'static str` (expected () but found &-ptr)
                 if i % 5 == 0 { "Buzz" },
                               ^~~~~~~~~~
error: mismatched types: expected `()` but found `<generic integer #0>` (expected () but found integral variable)
                 if !(i % 3 == 0 || i % 5 == 0) {
                     i
                 });

较新版本的Rust略有修改错误消息:

error[E0317]: if may be missing an else clause
 --> src/main.rs:7:13
  |
7 |             if i % 3 == 0 { "Fizz" },
  |             ^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found &str
  |
  = note: expected type `()`
             found type `&str`

error[E0317]: if may be missing an else clause
 --> src/main.rs:8:13
  |
8 |             if i % 5 == 0 { "Buzz" },
  |             ^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found &str
  |
  = note: expected type `()`
             found type `&str`

error[E0317]: if may be missing an else clause
 --> src/main.rs:9:13
  |
9 |             if !(i % 3 == 0 || i % 5 == 0) { i },
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found integral variable
  |
  = note: expected type `()`
             found type `{integer}`

我找到why does removing return give me an error: expected '()' but found,但按建议添加return没有帮助。

这些错误意味着什么,以及如何在将来避免这些错误?

1 个答案:

答案 0 :(得分:8)

问题在于if i % 3 == 0 { "Fizz" }会返回单位()&'static str。更改if表达式以在两种情况下返回相同的类型,例如通过添加else { "" }