- 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.
- Web應用系統開發實踐(C#)
- Mastering JavaScript Functional Programming
- Java從入門到精通(第4版)
- 大學計算機基礎(第2版)(微課版)
- Responsive Web Design by Example
- PhoneGap:Beginner's Guide(Third Edition)
- 數據結構習題解析與實驗指導
- MATLAB 2020從入門到精通
- Protocol-Oriented Programming with Swift
- Python算法詳解
- 響應式架構:消息模式Actor實現與Scala、Akka應用集成
- JavaScript程序設計(第2版)
- 軟件測試綜合技術
- JavaScript+jQuery網頁特效設計任務驅動教程
- Java程序設計與項目案例教程