为什么编译器假设 if let 的值应该是`()`? [英] Why does the compiler assume that the value of if let should be `()`?

查看:38
本文介绍了为什么编译器假设 if let 的值应该是`()`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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) 之后删除分号时,出现编译器错误:

It works properly, but when I remove the semicolon after found.insert(tr), I get a compiler error:

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`

这段代码位于何处或者它是否是函数的最后一个表达式都没有关系.

It doesn't matter where this code is located or whether it is the last expression of the function.

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

Why does the compiler assume that the expression inside the curly braces should be ()?

推荐答案

根据 Rust Book(强调我的):

表达式的值是选择的分支中最后一个表达式的值.没有 elseif 总是导致 () 作为值.

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.

这对花括号内的表达式值给出了一个约束.

This gives a constraint on the expression value inside the curly braces.

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

This is correct since the expression type matches ():

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

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

This is correct since there's an else statement (and the types between the branches match):

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

但这是错误的:

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

这个答案的灵感来自 此评论.

This answer was inspired by this comment.

这篇关于为什么编译器假设 if let 的值应该是`()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆