Skip to content

Borrow checker error in fixed code for map_entry lint #14154

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

Closed
mwylde opened this issue Feb 5, 2025 · 0 comments
Closed

Borrow checker error in fixed code for map_entry lint #14154

mwylde opened this issue Feb 5, 2025 · 0 comments
Labels
C-bug Category: Clippy is not doing the correct thing I-false-positive Issue: The lint was triggered on code it shouldn't have

Comments

@mwylde
Copy link

mwylde commented Feb 5, 2025

Summary

clippy --fix, while trying to address a clippy::map_entry lint, introduces a "cannot borrow *self as immutable because it is also borrowed as mutable" compiler error.

Lint Name

map_entry

Reproducer

Here is a minimal reproduction:

use std::collections::HashMap;

struct A {
    m: HashMap<String, String>,
}

impl A {
    fn make(&self) -> String {
        "v".to_string()
    }

    fn f(&mut self, k: String) {
        if !self.m.contains_key(&k) {
            self.m.insert(k, self.make());
        }
    }
}

fn main() {
    let mut a = A { m: HashMap::new() };
    a.f("k".to_string());
}

clippy --fix replaces f with

    fn f(&mut self, k: String) {
        self.m.entry(k).or_insert_with(|| self.make());
    }

which causes a compilation error

error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable
  --> src/main.rs:13:40
   |
13 |         self.m.entry(k).or_insert_with(|| self.make());
   |         ------          -------------- ^^ ---- second borrow occurs due to use of `*self` in closure
   |         |               |              |
   |         |               |              immutable borrow occurs here
   |         |               mutable borrow later used by call
   |         mutable borrow occurs here

Version

rustc 1.84.0 (9fc6b4312 2025-01-07)
binary: rustc
commit-hash: 9fc6b43126469e3858e2fe86cafb4f0fd5068869
commit-date: 2025-01-07
host: aarch64-apple-darwin
release: 1.84.0
LLVM version: 19.1.5

Additional Labels

No response

@mwylde mwylde added C-bug Category: Clippy is not doing the correct thing I-false-positive Issue: The lint was triggered on code it shouldn't have labels Feb 5, 2025
@mwylde mwylde closed this as completed Feb 5, 2025
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 I-false-positive Issue: The lint was triggered on code it shouldn't have
Projects
None yet
Development

No branches or pull requests

1 participant