- Rust Quick Start Guide
- Daniel Arbuckle
- 457字
- 2021-06-10 19:46:05
Block expressions
Sometimes, the necessary steps to figure out an expression's result value just don't fit into a single expression of the sorts we've looked at before. Maybe they need to store a data value for a little while in order to execute efficiently, or are otherwise too complex to be reasonably written in the 1 + ((2 * 57) / 13) style.
That's where block expressions come in. Block expressions look a lot like the body of a function because the body of a function is a block expression. They start with { and end with }. Between those two markers, we can write whatever instructions we need, including doing things like defining variables or other named items.
At the very end of the block should come the expression that produces the final result value of the block. So, for example, the block expression { 2 + 2; 19 % 3; println!("In a block"); true} is a (kind of silly) block expression that produces the Boolean true as its result, but not until after it has calculated that 2 plus 2 equals 4, and calculated that the remainder of 19 over 3 is 1, and printed out In a block to the console.
Notice the semicolons (;) in the block expression. Every top-level instruction in the block has a semicolon after it, except the last one. That's because the semicolon tells Rust that the expression before it should be treated as a statement, which basically means that it won't produce a value, or if it does, we don't care what that value is. In some cases, the semicolon can be left off of expressions prior to the last one in a block, but I don't recommend it, because explicitly discarding the results of expressions whose results we're not going to use allows the compiler more freedom to make inferences and optimizations, and can help avoid some fairly obscure compiler errors.
If we put a ; after the final expression in a block, we're saying that the block doesn't have a meaningful resulting value at all. In that case, it ends up having () as its resulting value. That's an empty tuple, which is a pretty good way of saying: Nothing to see here, folks. () is used that way throughout the Rust language and libraries.
- 嵌入式軟件系統(tǒng)測(cè)試:基于形式化方法的自動(dòng)化測(cè)試解決方案
- Beginning C++ Game Programming
- Visual C++串口通信開發(fā)入門與編程實(shí)踐
- 從程序員到架構(gòu)師:大數(shù)據(jù)量、緩存、高并發(fā)、微服務(wù)、多團(tuán)隊(duì)協(xié)同等核心場(chǎng)景實(shí)戰(zhàn)
- Processing互動(dòng)編程藝術(shù)
- Python 3破冰人工智能:從入門到實(shí)戰(zhàn)
- JavaScript入門經(jīng)典
- INSTANT Sinatra Starter
- Babylon.js Essentials
- Python語(yǔ)言實(shí)用教程
- Java Web應(yīng)用開發(fā)給力起飛
- Python函數(shù)式編程(第2版)
- 零基礎(chǔ)學(xué)HTML+CSS第2版
- Python機(jī)器學(xué)習(xí)與量化投資
- 征服C指針(第2版)