Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clippy::option_if_let_else recommends code that fails borrow check. #6060

Closed
harrysarson opened this issue Sep 17, 2020 · 1 comment
Closed
Labels
C-bug Category: Clippy is not doing the correct thing

Comments

@harrysarson
Copy link

I tried this code:

#![warn(clippy::pedantic)]

struct B(String);

fn f(optional: Option<B>) -> String {
    let b1 = B("!!".to_string());
    if let Some(b2) = optional {
        b1.0 + &b2.0
    } else {
        b1.0
    }
}

// fn f_as_recommended(optional: Option<B>) -> String {
//     let b1 = B("!!".to_string());
//     optional.map_or(b1.0, |b2|  b1.0 + &b2.0)
// }

fn main() {
    println!("{}", f(None));
}

Which gives the following cargo clippy output

    Checking playground v0.0.1 (/playground)
warning: use Option::map_or instead of an if let/else
  --> src/main.rs:7:5
   |
7  | /     if let Some(b2) = optional {
8  | |         b1.0 + &b2.0
9  | |     } else {
10 | |         b1.0
11 | |     }
   | |_____^ help: try: `optional.map_or(b1.0, |b2| b1.0 + &b2.0)`
   |
note: the lint level is defined here
  --> src/main.rs:1:9
   |
1  | #![warn(clippy::pedantic)]
   |         ^^^^^^^^^^^^^^^^
   = note: `#[warn(clippy::option_if_let_else)]` implied by `#[warn(clippy::pedantic)]`
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#option_if_let_else

warning: 1 warning emitted

    Finished dev [unoptimized + debuginfo] target(s) in 0.32s

But when I apply clippy's suggestion, borrow checking rightly rejects by code because both closures try to move the value of b1 (and the compiler cannot know that only one closure will ever be called`.

Meta

  • clippy 0.0.212 (2020-09-16 285fc7d): (from playground)
  • rustc 1.46.0 stable or 1.48.0-nightly (2020-09-16 285fc7d704fcdd7b2a37): (from playground)
@harrysarson harrysarson added the C-bug Category: Clippy is not doing the correct thing label Sep 17, 2020
@harrysarson
Copy link
Author

Oops, duplicate of #5822

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: Clippy is not doing the correct thing
Projects
None yet
Development

No branches or pull requests

1 participant