Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect claim that the number of lines in an arm require braces #4198

Open
bkline opened this issue Jan 10, 2025 · 0 comments
Open

Incorrect claim that the number of lines in an arm require braces #4198

bkline opened this issue Jan 10, 2025 · 0 comments

Comments

@bkline
Copy link

bkline commented Jan 10, 2025

URL to the section(s) of the book with this problem:

https://doc.rust-lang.org/book/ch06-02-match.html#the-match-control-flow-construct

Description of the problem:

If you want to run multiple lines of code in a match arm, you must use curly brackets, and the comma following the arm is then optional.

It turns out, according to the compiler, the condition which triggers the requirement for the curly brackets is not the fact that the code for the arm is spread over multiple lines. This version, putting everything on the same line for the arm:

Coin::Penny => println!("Lucky penny!"); 1

results in the error message "these statements are not surrounded by a body" indicating the portion of the line beginning with println!.

Conversely, spreading a single expression over multiple lines without enclosing the expression in curly braces compiles and runs just fine.

Suggested fix:

That depends on how the conflict between the earlier portions of the book (which assert that the value at the end of the line (without a semicolon) is an expression, not a statement) and the error message (which claims that it is a statement) should be resolved. If the compiler's message is correct, then the reworded sentence should read

If you want to include multiple statements in a match arm, you must use curly brackets, ...

Otherwise (that is, the book is right in saying 1 is an expression and not a statement), then it should read

If you want to include one or more statements in a match arm, you must use curly brackets, ...

I'm inclined to think the error message emitted by the compiler is just being sloppy in its wording, and the book's description of the distinction between a statement and an expression is correct, as that would match the semantics of those words as used for other languages. Regardless of which is correct, it is not correct to say that spreading an arm over multiple lines causes the compiler to require the use of braces.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant