How to work independently borrow with .or_insert_with card? Rust (1.11)

This snippet

use std::collections::HashMap;

struct Foo {
    local_ids: HashMap<i32, i32>,
    last_id: i32,
}

impl Foo {
    fn foo(&mut self, external_id: i32) {
        let id = self.local_ids
                     .entry(external_id)
                     .or_insert_with(||{self.last_id += 1; self.last_id});
    }
}

Doesn't work because we can't lend ourselves twice

error: closure requires unique access to `self` but `self.local_ids` is already borrowed [E0500]

Is it possible to fix this without looking for a second key?


This is very similar to Rust: the problem with the HashMap when trying to implement find or insert , but the API has changed significantly.

The find_with_or_insert_with answer above does not map to the current api.

+4
source share
1 answer

The problem is that the closure captures self, while it only needs to capture the mutable link in the field last_id.

Rust , last_id .

use std::collections::HashMap;

struct Foo {
    local_ids: HashMap<i32, i32>,
    last_id: i32,
}

impl Foo {
    fn foo(&mut self, external_id: i32) {
        let last_id = &mut self.last_id;
        let id = self.local_ids
                     .entry(external_id)
                     .or_insert_with(|| { *last_id += 1; *last_id });
    }
}

self.last_id , self , Rust , , .

+5

Source: https://habr.com/ru/post/1658635/