Skip to content

Type error for loops in a non-() position moves to the break statement #51669

Closed

Description

Rust has support for break within loop returning a value:

let x = loop {
 // ...
 break 5;
}

This is a relatively less-known feature.

If your loop is in a position where a type other than unit is expected, breaks in the loop may get a rather weird error (playpen)

fn foo() -> u8 {
    loop {
        // ...
        if true {
            break;
        }
        // ...
    }
}
error[E0308]: mismatched types
 --> src/main.rs:7:13
  |
7 |             break;
  |             ^^^^^ expected (), found u8
  |
  = note: expected type `()`
             found type `u8`

This error makes sense if you know that break can take a value, but most people don't, and this makes it kinda confusing. We should have better diagnostics here, perhaps move the primary error to the loop itself and add a note to the break, or vice versa.

(found by @jubitaneja)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-inferenceArea: Type inference

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions