Skip to content

Improve "if and else have incompatible types" error #57348

Closed
@estebank

Description

@estebank

When if and else arms have incompatible types, like below, the compiler should point at both arms with the evaluated type and also suggest removal of trailing semicolon if relevant.

fn main() {
    let a = if false { "x" } else { "y"; };
}

Current:

error[E0308]: if and else have incompatible types
 --> src/main.rs:2:13
  |
2 |     let a = if false { "x" } else { "y"; };
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected &str, found ()
  |
  = note: expected type `&str`
             found type `()`

Suggested:

error[E0308]: if and else have incompatible types
 --> src/main.rs:2:13
  |
2 |     let a = if false { "x" } else { "y"; };
  |                        ---          ^^^- help: remove this semicolon
  |                        |              |
  |                        |              expected &str, found ()
  |                        this arm evaluates to &str
  = note: expected type `&str`
             found type `()`

Example taken from lessons learned in Converting a Python library to Rust article

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions