簡體   English   中英

使用if表達式時,“不匹配的類型:預期的())是什么意思?

[英]What does “mismatched types: expected `()`” mean when using an if expression?

我試圖在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}`

我發現為什么刪除return會給我一個錯誤:預期為'()',但是找到了 ,但是按建議添加return並沒有幫助。

這些錯誤是什么意思,將來如何避免?

問題是, if i % 3 == 0 { "Fizz" }返回unit ()&'static str 更改if表達式以在兩種情況下返回相同的類型,例如,通過添加else { "" }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM