Insert value in hashmap when referencing values

Hi, I need a register over some named complex data. I use a hash map for that so I can easily fetch the data by name.

During runtime new data can be added, data can never be removed.

A simplification of the problem is this:

    let mut map = HashMap::new();
    map.insert(0, "value".to_owned());

    // Get reference (immutable borrow)
    let reference = map.get(&0).unwrap();

    // Insert value to hashmap (mutable borrow, not possible)
    map.insert(1, "value2".to_owned());

    println!("{:?}", reference);

Here is a little bigger example to get the whole context:

Is it possible to circumvent this check somehow?
I will never modify data in the hashmap, only add to it.

HashMap::insert() can move existing values via robin hood probing or growing the backing array. You need to re-lookup the hashmap after the insertion.

1 Like

Ah interesting! Then this approach is not going to work.

Maybe a linked list will work instead, but that also require mutability when I have immutable references so think that will result in the same thing.

You can put the values in Rc or Arc, then a clone is cheap when you want to break the reference.

1 Like

Thanks, that worked!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.