知识卡片
块的值来自尾表达式
块可以由语句加尾表达式组成。示例 { let x = 3; x + 1 } 的值是 4。把 x + 1 写成带分号的语句,会让块得到 (),与声明返回整数的函数不相容。需要中途离开函数时,用显式 return。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 常见编程概念 Functions · 查看原书依据
Functions can return values to the code that calls them. We don’t name return values, but we must declare their type after an arrow (->). In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function.
参考来源
- 位置:《The Rust Programming Language(第2版)》第03章 常见编程概念(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c03.xhtml`,块 0199)
- 结论依据:原文将函数返回值与函数体最后的表达式等同,并指出 return 可早退。
- 原始内容:Functions can return values to the code that calls them. We don’t name return values, but we must declare their type after an arrow (->). In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function.