I tried to implement fizzbuzz in Rust and failed with some cryptic 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
});
Or in newer versions of Rust with a slightly modified error message:
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 `_`
I found why removing return gives me an error: expected '()', but found , but adding return, as suggested, did not help.
What do these errors mean and how can I avoid them in the future?
source
share