Skip to content

map_entry false positive when map needs to be used while still borrowed by the entry #4674

Closed
@yanchith

Description

@yanchith

Hello, thanks for developing clippy! Ran into this (I believe) false positive in the map_entry lint:

The following function triggers the lint, but the suggestion (using entry) correctly triggers a borrowchecker error due to the map being borrowed by the entry.

/// Does compile, but triggers clippy::map_entry false positive
fn main() {
    let mut m: HashMap<u32, u32> = HashMap::new();
    let k: u32 = 0;
    if !m.contains_key(&k) {
        let value = compute_the_answer_possibly_with_map(&m);
        m.insert(k, value);
    }
}
/// Does not compile due to the entry having long lived
/// mutable borrow
fn main() {
    let mut m: HashMap<u32, u32> = HashMap::new();
    let k: u32 = 0;
    if let Entry::Vacant(vacant) = m.entry(k) {
        // Doesn't matter whether mutable or shared, this borrow is rejected!
        let value = compute_the_answer_possibly_with_map(&m);
        vacant.insert(value);
    }
}

The value computation can not be moved before the lookup - the point of the lookup is to prevent the computation from happening.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=16a29ebce3e1f3ce4fdd5676052e6914

Clippy version: clippy 0.0.212 (3aea8603 2019-09-03)

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-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions