gpt4 book ai didi

rust - "mismatched types: expected ` ( )`"在使用 if 表达式时意味着什么?

转载 作者:行者123 更新时间:2023-11-29 08:33:34 25 4
gpt4 key购买 nike

我尝试在 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}`

我找到了 why does removing return give me an error: expected '()' but found ,但按照建议添加 return 没有帮助。

这些错误是什么意思,以后我该如何避免这些错误?

最佳答案

问题是 if i % 3 == 0 { "Fizz"} 返回单元 ()&'static str .更改 if 表达式以在两种情况下返回相同的类型,例如通过添加 else { ""}

关于rust - "mismatched types: expected ` ( )`"在使用 if 表达式时意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com