官术网_书友最值得收藏!

  • 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.

By the way, the Rust compiler will warn us about that block expression, because it calculates two values and then just discards them. That's wasteful, so Rust points it out. If optimizations are enabled, the compiler will actually skip generating code to calculate the values at all, but that's an optimization, and the program and compiler are still supposed to act as if they did perform the calculations.

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.

主站蜘蛛池模板: 泰来县| 沙洋县| 齐齐哈尔市| 馆陶县| 原平市| 黄浦区| 镇雄县| 黑水县| 化州市| 秭归县| 长治县| 清镇市| 公主岭市| 江城| 葵青区| 启东市| 湄潭县| 肥乡县| 扎鲁特旗| 陈巴尔虎旗| 鄱阳县| 斗六市| 太仓市| 安龙县| 太湖县| 临海市| 石首市| 珠海市| 茂名市| 乐业县| 梁河县| 康马县| 宁明县| 遂平县| 泗阳县| 焦作市| 辽宁省| 隆子县| 兖州市| 辉县市| 葫芦岛市|