- Learning Rust
- Paul Johnson Vesa Kaihlavirta
- 337字
- 2021-07-02 23:07:25
What is the difference between having and not having a semicolon?
In Rust, almost everything is an expression. This means that almost everything returns a value. One exception is the variable binding statement let. In a let statement, and many others, the ending semicolon is a mandatory part of the syntax.
However, in expressions, the semicolon has a double role: it throws away a return value of the expression in addition to allowing further expressions. So if the expression is the last in a block, having a semicolon there means that the last value is thrown away, and not having a semicolon there means to return the last value.
An example should make it clear:
// 04/semicolon_block/src/main.rs
fn main() { let x = 5u32; let y = { let x_squared = x * x; let x_cube = x_squared * x; x_cube + x_squared + x }; let z = { 2 * x; }; println!("x is {:?}", x); println!("y is {:?}", y); println!("z is {:?}", z); }
We have two different uses of the semicolon. Let's look at the let y line first:
let y = { let x_squared = x * x; let x_cube = x_squared * x; x_cube + x_squared + x // no semi-colon };
This code does the following:
- The code within the braces is processed
- The final line, without the semicolon, is assigned to y
Essentially, this is considered as an inline function that returns the line without the semicolon into the variable.
The second line to consider is for z:
let z = { 2 * x; };
Again, the code within the braces is evaluated. In this case, the line ends with a semicolon, so the result is thrown away and the empty value () gets bound to z.
When it is executed, we will get the following results:

In the code example, the line within fn main calling recurse gives the same result with or without the semicolon, because the Rust runtime doesn't use main's return value for anything.
- 玩轉(zhuǎn)Scratch少兒趣味編程
- Learn Blockchain Programming with JavaScript
- R語(yǔ)言數(shù)據(jù)分析從入門(mén)到精通
- CMDB分步構(gòu)建指南
- Vue.js快速入門(mén)與深入實(shí)戰(zhàn)
- VMware vSphere 6.7虛擬化架構(gòu)實(shí)戰(zhàn)指南
- GitLab Repository Management
- Spring實(shí)戰(zhàn)(第5版)
- 從學(xué)徒到高手:汽車(chē)電路識(shí)圖、故障檢測(cè)與維修技能全圖解
- 青少年P(guān)ython編程入門(mén)
- 快速念咒:MySQL入門(mén)指南與進(jìn)階實(shí)戰(zhàn)
- 零基礎(chǔ)趣學(xué)C語(yǔ)言
- Swift 4從零到精通iOS開(kāi)發(fā)
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設(shè)計(jì)原理(第2版)
- SciPy Recipes