Skip to content

Detect type mismatch due to loop that might never iterate #98982

Closed
@estebank

Description

@estebank

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

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-papercutDiagnostics: An error or lint that needs small tweaks.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions