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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.240