Skip to content

suggest Ok-wrapping for ?-originating type mismatch when (and only when) applicable #55429

Description

@zackmdavis

Sometimes E0308 on a try-expression can be fixed by wrapping with Ok. This is a somewhat common mistake in the form of a ?-expression appearing in tail position of a function that is expected to Result

fn foo() -> Result<isize, ()> {
     Ok(1)
}
 
fn bar() -> Result<isize, ()> {
    foo()? // `Ok(foo()?)` would work
}

fn main() {}

However, not all type mismatches on ? are like this. Here's a negative example—

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

fn try_it() -> Result<String, ()> {
    let n: i32 = maybe_numbers()?; // `Ok(maybe_numbers()?)` is not the right move here
    Ok(format!("{:?}", n))
}

fn main() {}

We want to suggest Ok-wrapping when that's the correct fix. (This issue is being filed because a previous attempt at this suggestion had too many false positives and is likely to be removed.)

See discussion on #52537 for one idea on how to proceed.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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