-
Notifications
You must be signed in to change notification settings - Fork 13.6k
Closed
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lints
Description
If I take the following line from the Rust book and make a function out of it
let secret_number = rand::thread_rng().gen_range(1, 101);
Meaning something like
let secret_number = generate_secret_number() ;
// ...
fn generate_secret_number() -> u32 {
rand::thread_rng().gen_range(1, 101);
}
Then the compiler fails with
src/main.rs:41:1: 45:2 error: not all control paths return a value [E0269]
src/main.rs:41 fn generate_secret_number() -> u32 {
src/main.rs:42 rand::thread_rng().gen_range(1, 101);
src/main.rs:43 }
src/main.rs:41:1: 43:2 help: run `rustc --explain E0269` to see a detailed explanation
error: aborting due to previous error
Could not compile `guessing_game`.
However if I add the return statement, which should be optional. It works
let secret_number = generate_secret_number() ;
// ...
fn generate_secret_number() -> u32 {
return rand::thread_rng().rnd.gen_range(1, 101);
}
Shouldn't this be considered an expression by the compiler?
Metadata
Metadata
Assignees
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lints
Type
Projects
Milestone
Relationships
Development
Select code repository
Activity
gereeter commentedon Dec 20, 2015
The crucial thing here is the semicolon after your statement. A block consists of a bunch of statements, terminated with semicolons, possibly followed by an expression, which is not terminated by a semicolon. Therefore, putting the semicolon after
rand::thread_rng().gen_range(1, 101)
made the compiler view the expression as a statement, with no terminating expression on the block. If you leave off the semicolon, it should work:Note the lack of a semicolon. I hope that helps!
This bug might still be useful as a documentation bug - the long explaination for
E0269
does not mention this pitfall, while it seems like a common case that should be addressed.jonas-schievink commentedon Dec 20, 2015
There's usually a suggestion printed telling you to remove the trailing semicolon. It only works when the type of the last statement-expression is the same as the function return type, which isn't known in this case since the return type of
gen_range
is inferred.cc #29396, which attempted to fix this
pjmlp commentedon Dec 20, 2015
I see, still getting the hang of when semicolons are required.
But maybe a clearer error message is required.
[-]Unreachable code in a single line function.[/-][+]Unclear error message with extra semicolon[/+]Aatch commentedon Dec 27, 2015
I updated the title to make it accurately reflect the issue. The compiler never considers the line to be unreachable either way, it just says that not all control paths return a value. Which is true, none of the 1 control paths return a value.
E0269: add suggestion to check for trailing semicolons