Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
955 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 { "" }.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...