我试图在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;
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
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
});
Run Code Online (Sandbox Code Playgroud)
较新版本的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}`
Run Code Online (Sandbox Code Playgroud)
我发现为什么删除返回给我一个错误:期望'()'但是找到了,但是return按照建议添加并没有帮助.
这些错误意味着什么,以及如何在将来避免它们?
问题是if i % 3 == 0 { "Fizz" }返回单位()或&'static str.更改if表达式以在两种情况下返回相同的类型,例如通过添加a else { "" }.
| 归档时间: |
|
| 查看次数: |
4596 次 |
| 最近记录: |