rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

`manual_ok_err` suggest incorrect fix for references

Open knoellle opened this issue 4 months ago • 0 comments

Summary

The manual_ok_err lint is listed as machine applicable but suggests an incorrect lint when the scrutinee involves references.

The hint (see reproducer) given after the incorrect suggestion is applied also doesn't work as the as_ref needs to be before the ok.

A similar error occurs when using mutable references, though the compiler does not suggest to use as_mut.

Lint Name

manual_ok_err

Reproducer

I tried this code:

fn main() {
    some_function(&Container { field: Ok(false) });
}

struct Container {
    field: Result<bool, ()>,
}

fn some_function(x: &Container) -> Option<&bool> {
    match &x.field {
        Ok(panel) => Some(panel),
        Err(_) => None,
    }
}

I saw this happen:

warning: manual implementation of `ok`
  --> src/main.rs:10:5
   |
10 | /     match &x.field {
11 | |         Ok(panel) => Some(panel),
12 | |         Err(_) => None,
13 | |     }
   | |_____^ help: replace with: `(&x.field).ok()`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#manual_ok_err
   = note: `#[warn(clippy::manual_ok_err)]` on by default

but (&x.field).ok() does not compile because the type is Option<bool> yet the function returns Option<&bool>:

  --> src/main.rs:10:5
   |
9  | fn some_function(x: &Container) -> Option<&bool> {
   |                                    ------------- expected `std::option::Option<&bool>` because of return type
10 |     (&x.field).ok()
   |     ^^^^^^^^^^^^^^^ expected `Option<&bool>`, found `Option<bool>`
   |
   = note: expected enum `std::option::Option<&_>`
              found enum `std::option::Option<_>`
help: try using `.as_ref()` to convert `std::option::Option<bool>` to `std::option::Option<&bool>`
   |
10 |     (&x.field).ok().as_ref()
   |                    +++++++++

I expected to see this happen:

No lint emitted or something with the following suggestion: x.field.as_ref().ok()

Version

rustc 1.87.0 (17067e9ac 2025-05-09)
binary: rustc
commit-hash: 17067e9ac6d7ecb70e50f92c1944e545188d2359
commit-date: 2025-05-09
host: x86_64-unknown-linux-gnu
release: 1.87.0
LLVM version: 20.1.1

Additional Labels

@rustbot label +I-suggestion-causes-error

knoellle avatar Jun 13 '25 23:06 knoellle