Closed SamLGill closed 5 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.
Would adding this context be helpful?
Note: the semicolon after
break counter * 2
is technically optional.break
is very similar toreturn
, in that both can optionally take an expression as an argument, both cause a change in control flow. Code after abreak
orreturn
is never executed, so the Rust compiler treats abreak
expression and areturn
expression as having the value unit, or()
.
Yes, I think that would be very helpful.
Looks like this can be closed now. Thanks for the new wording!
Thanks!
main
branch to see if this has already been fixedURL 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.