gpt4 book ai didi

rust - 通过 if 语句绑定(bind)的变量无法正常工作

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

我写了这段代码:

let x = 5;
let y = if x == 5 {
10
} else {
println!("shapoopoy");
};

当我使用 cargo build 编译时,出现错误:

error[E0308]: if and else have incompatible types
--> src/main.rs:6:9
|
3 | let y = if x == 5 {
| _____________-
4 | | 10
| | -- expected because of this
5 | | } else {
6 | | println!("shapoopoy");
| | ^^^^^^^^^^^^^^^^^^^^^^ expected integer, found ()
7 | | };
| |_____- if and else have incompatible types
|
= note: expected type `{integer}`
found type `()`

附带说明一下,如果我计划在学习 Rust 之后从事一个项目,我应该坚持使用稳定版本吗?如果我确实使用旧版本,我不确定如何将 Rust 包含在我制作的程序中。

最佳答案

让我们看看您的示例代码:

let x = 5;
let y = if x == 5 {
10
} else {
println!("shapoopoy");
};

y类型 是什么?第一个分支解析为一些整型变量(如 u8i32),但第二个分支解析为 println! 的返回类型,它是 ()。您不能在一个空间中存储两种这两种类型,因此编译器会报错。

两个分支都需要解析为相同的类型——这取决于您需要做什么。您可以不返回任何内容,并将变量设置为副作用:

let x = 5;
let y;

if x == 5 {
y = 10;
} else {
println!("shapoopoy");
}

或者在两个分支中都返回一个整数:

let x = 5;
let y = if x == 5 {
10
} else {
println!("shapoopoy");
42
};

I'm not sure how to include Rust with the program I make if I do use an older version.

Rust 是一种编译语言。如果您分发已编译的二进制文件,那么您根本不需要“包含”Rust。如果您选择稳定版本,那么您始终可以固定到该版本的 Rust 并使用它进行编译。

关于rust - 通过 if 语句绑定(bind)的变量无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200304/

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