cognitive-engineering-lab / rust-book

The Rust Programming Language: Experimental Edition
https://rust-book.cs.brown.edu
Other
504 stars 82 forks source link

Example in 3.5 leaves out explanation of semicolon usage within loop curly brackets #140

Closed SamLGill closed 5 months ago

SamLGill commented 7 months ago

URL to the section(s) of the book with this problem: https://rust-book.cs.brown.edu/ch03-05-control-flow.html#repeating-code-with-loop

Description of the problem: In the example used to show repeating a code with loop which then assigns a value to result, there is a semi-colon at the end of "break counter * 2;" This semi-colon is not explained. I am a first time rust learner and have been meticulously following this book to learn and it seems to me that it has been made abundantly clear that ending a line with a semi-colon makes it a statement, not an expression (ergo not able to be a returned value of a block of code or able to be assigned to a variable{. Every other example of a curly brace block of code which returns a value has the line which returns the value to not end with a semi-colon. Obviously, the code compiles and runs, and after testing myself, it appears it compiles and runs exactly the same way whether or not there is a semi-colon. I am confused and wish there had been an explanation of this phenomenon.

Suggested fix: Explain why it is there and why it compiles properly either way and why it doesn't follow the same rules as other blocks of codes.

jetlime commented 6 months ago

I had the exact same thought while reading this example as well! I agree with the suggested fix. The break token is an expression, returning any statement that is followed by it. We could include one sentence explaining, that in this specific case, the semi-colon is optional (since the break makes it an expression anyway), or modify the example by omitting the semi-colon.

willcrichton commented 5 months ago

Would adding this context be helpful?

Note: the semicolon after break counter * 2 is technically optional. break is very similar to return, in that both can optionally take an expression as an argument, both cause a change in control flow. Code after a break or return is never executed, so the Rust compiler treats a break expression and a return expression as having the value unit, or ().

SamLGill commented 5 months ago

Yes, I think that would be very helpful.

nk9 commented 5 months ago

Looks like this can be closed now. Thanks for the new wording!

SamLGill commented 5 months ago

Thanks!