gpt4 book ai didi

rust - 为什么编译器假设 if let 的值应该是 `()` ?

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

我有以下代码:

use std::collections::HashSet;

fn translate() -> Option<String> {
None
}

fn main() {
let mut found = HashSet::new();

if let Some(tr) = translate() {
found.insert(tr);
}
}

它工作正常,但是当我删除 found.insert(tr) 之后的分号时,出现编译错误:

error[E0308]: mismatched types
--> src/main.rs:11:9
|
7 | fn main() {
| - expected `()` because of default return type
...
11 | found.insert(tr)
| ^^^^^^^^^^^^^^^^- help: try adding a semicolon: `;`
| |
| expected (), found bool
|
= note: expected type `()`
found type `bool`

这段代码位于何处或者它是否是函数的最后一个表达式都无关紧要。

为什么编译器假定大括号内的表达式应该是 ()

最佳答案

根据Rust Book (强调我的):

The value of the expression is the value of the last expression in whichever branch was chosen. An if without an else always results in () as the value.

这对花括号内的表达式值进行了约束。

这是正确的,因为表达式类型匹配 ():

if let Some(_) = some() {
()
};

这是正确的,因为有一个 else 语句(并且分支之间的类型匹配):

if let Some(_) = some() {
true
} else {
false
};

但这是错误的:

if let Some(_) = some() {
true
};

这个答案的灵感来自 this comment .

关于rust - 为什么编译器假设 if let 的值应该是 `()` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37646475/

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