“不匹配的类型:预期的‘()’"是什么意思?使用 if 表达式时是什么意思? [英] What does "mismatched types: expected `()`" mean when using an if expression?
问题描述
我尝试在 Rust 中实现 fizzbuzz,但由于一些神秘的错误而失败:
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: 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
});
较新版本的 Rust 有一个稍微修改的错误消息:
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}`
我发现 为什么删除返回给我有一个错误:预期的 '()' 但找到了,但是按照建议添加 return
没有帮助.
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?
推荐答案
问题在于 if i % 3 == 0 { "Fizz" }
返回任一单元 ()
或 &'static str
.更改 if 表达式以在两种情况下返回相同的类型,例如添加 else { "" }
.
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 { "" }
.
这篇关于“不匹配的类型:预期的‘()’"是什么意思?使用 if 表达式时是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!