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

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.

主站蜘蛛池模板: 济阳县| 剑河县| 东平县| 阳谷县| 曲水县| 北川| 同江市| 漳浦县| 睢宁县| 蒙城县| 奉化市| 多伦县| 金塔县| 泸溪县| 赞皇县| 平顶山市| 临泉县| 广丰县| 日喀则市| 舒兰市| 会昌县| 靖远县| 建德市| 海南省| 秦安县| 嘉善县| 衡水市| 库伦旗| 镶黄旗| 岑溪市| 秭归县| 繁昌县| 包头市| 育儿| 海丰县| 依兰县| 个旧市| 扶余县| 扶沟县| 开阳县| 德兴市|