Skip to content

question_mark suggestion changes code semantics #9518

@divagant-martian

Description

@divagant-martian

Summary

If let expression that produces a result is suggested to change to ?, changing the semantics of the code

Lint Name

question_mark

Reproducer

I tried this code:

fn do_stuff() -> Result<(), ()> {
    let result = if let Err(e) = op1() { Err(e) } else { Ok(()) };

    do_something_with_result(&result);

    result
}

fn op1() -> Result<(), ()> {
    Err(())
}

fn do_something_with_result(arg: &Result<(), ()>) {
    println!("doing something with the result {arg:?}");
}

fn main() {
    do_stuff().unwrap();
}

}

I saw this happen:

warning: this block may be rewritten with the `?` operator
 --> src/main.rs:2:18
  |
2 |     let result = if let Err(e) = op1() { Err(e) } else { Ok(()) };
  |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `op1()?`
  |
  = note: `#[warn(clippy::question_mark)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#question_mark

I expected to see this happen:
There should be no warning. Changing the code for what clippy suggests would prevent calling do_something_with_result when the result is an error

Version

rustc 1.64.0 (a55dd71d5 2022-09-19)
binary: rustc
commit-hash: a55dd71d5fb0ec5a6a3a9e8c27b2127ba491ce52
commit-date: 2022-09-19
host: x86_64-unknown-linux-gnu
release: 1.64.0
LLVM version: 14.0.6

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions