rust-lang / book

The Rust Programming Language

Home Page:https://doc.rust-lang.org/book/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

3.5 control flow - Expression vs Statement in loop

cwoz117 opened this issue · comments

  • I have searched open and closed issues and pull requests for duplicates, using these search terms:

    • 11 closed w/ 3.5 and none relate to the find.
  • I have checked the latest main branch to see if this has already been fixed, in this file:

    • issue still exists in main

URL to the section(s) of the book with this problem:
https://github.com/rust-lang/book/blob/main/listings/ch03-common-programming-concepts/no-listing-33-return-value-from-loop/src/main.rs#L8

Description of the problem:
We need an Expression for a return value, but a semicolon is provided. This contradicts 3.3 functions where we learn that adding a semicolon turns an expression into a statement, which should not have a return value.

This compiles and runs in both cases, just seemed inconsistent with the last page as is.

Suggested fix:
Remove the semicolon to remain consistent with the Expression vs Statement definitions in 3.3.

I want to contribute to this issue.

Thanks for opening this. The book example code is correct here, though. The line is a break statement, but a break statement takes an optional expression, and the value of the loop is that expression. Alternatively, you could think of it as break always taking a value; when you don’t put anything there, it is implicitly (), just like a function which does not return a non-() value.