← 返回起始笔记位置

知识卡片

普通读书笔记卡 · 6074.d.6.b · 生成模型:未记录

块的尾表达式给出值

理解等级:初级

块可像普通表达式一样放在赋值右边或 match 分支中。若最后一个表达式没有分号,块使用该表达式的值。写成 { work(); result() } 时会得到 result() 的结果,写成 { work(); result(); } 时得到单位值 ()。无 else 的 if 本身要求 (),所以漏写分号时常看到类型不匹配。

关联阅读:[[分支结果也是表达式值]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)》第05章《Expressions》|通过尾表达式或标签退出给出块的值,来源项目 `book-source`,`extracted/Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)/_epub-src/OEBPS/ch05.xhtml#blocks` - 结论依据:原文从没有分号的 ip.to_string() 得到块返回值,并给出无 else 的 if 因尾元组而报错的示例。 - 原始内容:The value of the block is the value of its last expression, ip.to_string().