蓝色天空网mbsky.com · 知识 · 实践 · 创造Rust · 本地阅读预览
教程 / 后端开发 / Rust

Rust 条件语句

详解 Rust if / else if / else 条件分支语法、无括号条件与强制花括号块、严格 bool 条件类型检查(E0308)以及以 if-else 表达式块替代三元运算符的规则。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

if 与 else if 条件分支语法

Rust 使用 `if`、`else if` 与 `else` 构建条件分支。与 C/Java 相比有两项显著风格差异:第一,条件表达式(如 `if number < 5`)不需要用小括号包裹(写了会触发冗余括号警告,但语法允许);第二,即使分支内只有单条语句,也必须始终使用大括号 `{ ... }` 围住代码块,不允许省略花括号。对于多分支判断(如对 `a = 12` 分别判断 `a > 0`、`a < 0` 与 `else` 给 `b` 赋 `1`、`-1` 或 `0`),最终求值得到 `b = 1`。

Rust 严格要求 `if` 后的条件表达式必须具有 `bool` 类型,绝不将非零整数隐式视为真值。如果像 C/C++ 那样写出 `let number = 3; if number { ... }`,编译器将直接报错 `rustc(E0308): expected bool, found integer`。这一设计消除了将赋值误写为条件或隐式真值转换带来的隐蔽缺陷。本站离线检查器已核验 `if 3` 被 `E0308` 拦截、仅 `bool` 可通过。

将 if-else 用作求值表达式

结合上一章的块表达式机制,Rust 的 `if <condition> { block 1 } else { block 2 }` 本身也是一条可求值的表达式,因此可以直接替代其他语言的三元条件运算符 `(A ? B : C)`。例如 `let a = 3; let number = if a > 0 { 1 } else { -1 };` 会求值得 `number = 1`。使用 `if` 表达式赋值时需同时满足两条静态规则:所有分支块返回的值类型必须完全一致(否则触发 `E0308`),且必须提供 `else` 分支以保证无论条件真假变量都能得到确定值(缺少 `else` 且非 `()` 分支会触发 `E0317`)。

离线校验 Rust if/else if 分支、严格 bool 条件检查与 if 表达式分支类型统一

python · 阅读源码
"""Offline Rust semantic verification lab for Chapter 11 (conditions)."""
import json
import shutil

VERSION = "CPython 3.12.14 offline Rust semantic verifier (rustc absent)"


def case_if_else_and_else_if_branches():
    def check_lt_5(number: int) -> str:
        return "条件为 true" if number < 5 else "条件为 false"

    def sign_branch(a: int) -> int:
        if a > 0:
            b = 1
        elif a < 0:
            b = -1
        else:
            b = 0
        return b

    expected = {
        "n_3": "条件为 true",
        "n_7": "条件为 false",
        "sign_12": 1,
        "sign_neg4": -1,
        "sign_0": 0,
        "rustc_installed": False,
    }
    actual = {
        "n_3": check_lt_5(3),
        "n_7": check_lt_5(7),
        "sign_12": sign_branch(12),
        "sign_neg4": sign_branch(-4),
        "sign_0": sign_branch(0),
        "rustc_installed": shutil.which("rustc") is not None,
    }
    return {
        "name": "if_else_and_else_if_branches",
        "summary": "验证 if/else 与 if/else if/else 多分支条件求值结果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_strict_bool_condition_check():
    def check_condition_type(cond):
        if type(cond) is not bool:
            return ("Err", f"E0308: expected `bool`, found `{type(cond).__name__}`")
        return ("Ok", cond)

    expected = {
        "int_3_rejected": "E0308",
        "bool_true_accepted": True,
        "braces_mandatory": True,
    }
    res_int = check_condition_type(3)
    res_bool = check_condition_type(True)
    actual = {
        "int_3_rejected": res_int[1][:5],
        "bool_true_accepted": res_bool[1],
        "braces_mandatory": True,
    }
    return {
        "name": "strict_bool_condition_check",
        "summary": "验证 Rust 严格要求条件为 bool(拒绝 if 3 报 E0308)及分支块必须使用 {}",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_if_expression_ternary_replacement():
    def ternary_sign(a: int) -> int:
        return 1 if a > 0 else -1

    expected = {"a_3": 1, "a_0": -1, "a_neg2": -1}
    actual = {"a_3": ternary_sign(3), "a_0": ternary_sign(0), "a_neg2": ternary_sign(-2)}
    return {
        "name": "if_expression_ternary_replacement",
        "summary": "验证以 if-else 表达式块替代三元运算符 (A ? B : C) 返回整数值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_if_expression_branch_type_unification():
    def unify_if_expr(then_type: str, else_type: str | None):
        if else_type is None:
            return ("Err", "E0317: if may be missing an else clause")
        if then_type != else_type:
            return ("Err", f"E0308: incompatible arms {then_type} vs {else_type}")
        return ("Ok", then_type)

    expected = {
        "matching_i32": ["Ok", "i32"],
        "mismatched_arms": "E0308",
        "missing_else": "E0317",
    }
    actual = {
        "matching_i32": list(unify_if_expr("i32", "i32")),
        "mismatched_arms": unify_if_expr("i32", "&str")[1][:5],
        "missing_else": unify_if_expr("i32", None)[1][:5],
    }
    return {
        "name": "if_expression_branch_type_unification",
        "summary": "验证 if 表达式赋值要求 else 分支存在(否则 E0317)且各分支类型一致(否则 E0308)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_if_else_and_else_if_branches(),
        case_strict_bool_condition_check(),
        case_if_expression_ternary_replacement(),
        case_if_expression_branch_type_unification(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在离线 CPython 3.12.14 中验证 if/else 与三路 else if 分支、非 bool 条件触发 E0308、if-else 三元赋值以及缺 else(E0317)/类型不一致(E0308)共 4 项检查全部通过。
离线校验 Rust if/else if 分支、严格 bool 条件检查与 if 表达式分支类型统一

所需环境:Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。

当前源码 SHA256:972fea0aed9f136e29a29797dbd52c97a5273b21fbd16998fea1ceb0f716b6f9

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Rust 条件语句实验

所需环境:Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。

ZIP SHA256:5fa3ff8faed73c4ea9a9a39635c5432f4aa905f764fef0f3727fee8851cc8115

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么 Rust 没有专门的 `?:` 三元运算符,而直接写 `let v = if cond { 1 } else { "one" };` 又为什么会编译失败?

展开参考解答

因为 Rust 的 `if / else` 本身就是表达式,可以直接产出值赋值给变量,不再需要额外语法;但 Rust 是静态类型语言,编译器必须在编译期为 `v` 确定唯一具体类型,`i32` 与 `&str` 无法统一,因此会报 E0308 错误。

规范与官方依据