Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "mismatched types: expected `()`" mean when using an if expression?

Tags:

rust

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?

like image 908
J V Avatar asked Jul 04 '14 19:07

J V


1 Answers

The problem is that if i % 3 == 0 { "Fizz" } returns either unit () or &'static str. Change the if expressions to return the same type in both cases, for example by adding a else { "" }.

like image 140
A.B. Avatar answered Sep 29 '22 07:09

A.B.