[英]What does “mismatched types: expected `()`” mean when using an if expression?
我试图在Rust中实现fizzbuzz,但由于一些不可思议的错误而失败:
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具有稍微修改的错误消息:
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会给我一个错误:预期为'()',但是找到了 ,但是按建议添加return
并没有帮助。
这些错误是什么意思,将来如何避免?
问题是, if i % 3 == 0 { "Fizz" }
返回unit ()
或&'static str
。 更改if表达式以在两种情况下返回相同的类型,例如,通过添加else { "" }
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.