我試圖實現鏽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,100){...}'而不是'while' +手動遞增。 – huon