Closed
Description
Given
fn foo() -> i32 {
for i in 0..0 {
return i;
}
}
the current output is
error[E0308]: mismatched types
--> src/lib.rs:2:5
|
1 | fn foo() -> i32 {
| --- expected `i32` because of return type
2 | / for i in 0..0 {
3 | | return i;
4 | | }
| |_____^ expected `i32`, found `()`
If a return
statement is present in the tail expression, and that tail expression is a loop, it should provide more information for newcomers:
error[E0308]: mismatched types
--> src/lib.rs:2:5
|
1 | fn foo() -> i32 {
| --- expected `i32` because of return type
2 | / for i in 0..0 {
3 | | return i;
4 | | }
| |_____^ expected `i32`, found `()`
note: the function expects a value to always be returned, but loops might run zero times
--> src/lib.rs:2:5
|
2 | for i in 0..0 {
| ^^^^ this might have zero elements to iterate on
3 | return i;
| - if the loop doesn't execute, this value would never get returned
help: return a value for the case when the loop has zero elements to iterate on, and consider changing the return type to account for that possibility
|
1 ~ fn foo() -> Option<i32> {
...
5 + None
|
Metadata
Metadata
Assignees
Labels
Area: Messages for errors, warnings, and lintsArea: Suggestions generated by the compiler applied by `cargo fix`Diagnostics: An error or lint that needs small tweaks.Diagnostics: An error or lint that doesn't give enough information about the problem at hand.Relevant to the compiler team, which will review and decide on the PR/issue.