2014-07-04 103 views
4

我試圖實現鏽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 
       }); 

或者在較新版本鏽用稍微修改的錯誤消息:

error: if may be missing an else clause [--explain E0308] 
        if i % 3 == 0 { "Fizz" }, 
        ^^^^^^^^^^^^^^^^^^^^^^^^ expected(), found &-ptr 
note: in this expansion of format_args! 
note: in this expansion of print! (defined in <std macros>) 
note: in this expansion of println! (defined in <std macros>) 
note: expected type `()` 
note: found type `&'static str` 

error: if may be missing an else clause [--explain E0308] 
       if i % 5 == 0 { "Buzz" }, 
       ^^^^^^^^^^^^^^^^^^^^^^^^ expected(), found &-ptr 
note: in this expansion of format_args! 
note: in this expansion of print! (defined in <std macros>) 
note: in this expansion of println! (defined in <std macros>) 
note: expected type `()` 
note: found type `&'static str` 

error: if may be missing an else clause [--explain E0308] 
       if !(i % 3 == 0 || i % 5 == 0) { 
       ^expected(), found integral variable 
note: in this expansion of format_args! 
note: in this expansion of print! (defined in <std macros>) 
note: in this expansion of println! (defined in <std macros>) 
note: expected type `()` 
note: found type `_` 

我發現why does removing return give me an error: expected '()' but found,但添加return建議沒有幫助。

這些錯誤意味着什麼,我將來如何避免它們?

+1

順便說一句,你應該在範圍使用'爲我(1,100){...}'而不是'while' +手動遞增。 – huon

回答

8

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

+0

然後我遇到了最後一個問題 - 如果我使用'i.to_str()'使它們成爲相同類型,我會得到'error:if和else有不兼容的類型:expected \'collections :: string :: String \ '但發現'&'static str \'(期望的結構集合:: string :: String但是找到&-ptr)' –

+0

'「」.to_str()'用於匹配最後一種情況的類型。順便說一句,一個更習慣的fizzbuzz會使用match和println!爲每個比賽手臂。查看當前嘗試工作後是否可以重構代碼。 –

+1

'to_str'和一個普通的'''''返回的字符串之間有什麼區別,是其中的一個盒裝? –

-1

就我而言,作爲初學者,我加了「;」在return聲明

fn add_one(x: i32) -> i32 { 
    x + 1; // remove ";" from return 
}