Skip to content

Invalid suggestion of option_if_let_else causes a compilation error error[E0382]: Borrow of moved value #6737

@xFrednet

Description

@xFrednet

I tried this code:

#[allow(dead_code, clippy::unnecessary_wraps)]
#[deny(clippy::option_if_let_else)]
fn test_fn(acc: Option<String>) -> Option<String> {
    // Computation of mv_value
    let mv_value = "Hello clippy".to_string();
    
    if let Some(mut x) = acc {
        x.push_str(&mv_value);
        Some(x)
    } else {
        Some(mv_value)
    }
}

and got the following lint trigger:

error: use Option::map_or instead of an if let/else
  --> src/main.rs:8:5
   |
8  | /     if let Some(mut x) = acc {
9  | |         x.push_str(&mv_value);
10 | |         Some(x)
11 | |     } else {
12 | |         Some(mv_value)
13 | |     }
   | |_____^
   |
note: the lint level is defined here
  --> src/main.rs:3:8
   |
3  | #[deny(clippy::option_if_let_else)]
   |        ^^^^^^^^^^^^^^^^^^^^^^^^^^
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#option_if_let_else
help: try
   |
8  |     acc.map_or(Some(mv_value), |mut x| {
9  |         x.push_str(&mv_value);
10 |         Some(x)
11 |     })
   |

Using the suggested code leads to:

error[E0382]: borrow of moved value: `mv_value`
  --> src/main.rs:16:32
   |
6  |     let mv_value = "Hello clippy".to_string();
   |         -------- move occurs because `mv_value` has type `String`, which does not implement the `Copy` trait
...
16 |     acc.map_or(Some(mv_value), |mut x| {
   |                     --------   ^^^^^^^ value borrowed here after move
   |                     |
   |                     value moved here
17 |         x.push_str(&mv_value);
   |                     -------- borrow occurs due to use in closure

Playground

The if let is used in this case to use mv_value in both branches. This is a limitation of the map_or suggestion.

Meta

  • cargo clippy -V: clippy 0.1.51 (3682750 2021-02-02)
  • rustc -Vv:
    rustc 1.51.0-nightly (368275062 2021-02-02)
    binary: rustc
    commit-hash: 368275062fb655c1f36e0398f88b15379a1f3c93
    commit-date: 2021-02-02
    host: x86_64-unknown-linux-gnu
    release: 1.51.0-nightly
    LLVM version: 11.0.1
    

Keep up the good work 📎 🐧

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.I-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when appliedL-pedanticLint: Belongs in the pedantic lint group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions