Skip to content

suggestion for E0308 "try expression alternatives have incompatible types" is sometimes wrong #52598

Closed
@zackmdavis

Description

@zackmdavis

In 6cc78bf / #51632, we reworded the error methods for type-mismatches-in-matches when the match comes from a ?-expression, and added a suggestion to Ok-wrap the expression. While that's often the right fix (notably, when a ?-expression is in tail position of a function that returns Result), sometimes it isn't. Here's a counterexample:

fn maybe_numbers() -> Result<Vec<i32>, ()> {
    Ok(vec![1, 2, 3])
}

fn try_it() -> Result<String, ()> {
    let n: i32 = maybe_numbers()?;
    Ok(format!("{:?}", n))
}

fn main() {}

Currently, we emit:

error[E0308]: try expression alternatives have incompatible types
 --> success_variant.rs:6:18
  |
6 |     let n: i32 = maybe_numbers()?;
  |                  ^^^^^^^^^^^^^^^^
  |                  |
  |                  expected i32, found struct `std::vec::Vec`
  |                  help: try wrapping with a success variant: `Ok(maybe_numbers()?)`
  |
  = note: expected type `i32`
             found type `std::vec::Vec<i32>`

We should, somehow, not issue the "try wrapping with a success variant" suggestion (which lives in librustc/infer/error_reporting/mod.rs) in cases like these.

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