I tried to implement fizzbuzz in Rust and failed with some arcane error:
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:
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
});
Newer versions of Rust have a slightly modified error message:
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}`
I found why does removing return give me an error: expected '()' but found, but adding return
as suggested didn't help.
What do these errors mean and how do I avoid them in the future?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…