I have the following code:
use std::collections::{HashMap, HashSet};
fn populate_connections(
start: i32,
num: i32,
conns: &mut HashMap
If you can guarantee that your two indices are different, you can use unsafe code and avoid interior mutability:
fn get_mut_pair<'a, K, V>(conns: &'a mut HashMap, a: &K, b: &K) -> (&'a mut V, &'a mut V)
where
K: std::fmt::Debug + Eq + std::hash::Hash,
{
unsafe {
assert_ne!(a, b, "`a` ({:?}) must not equal `b` ({:?})", a, b);
let a = conns.get_mut(a).unwrap() as *mut _;
let b = conns.get_mut(b).unwrap() as *mut _;
(&mut *a, &mut *b)
}
}
This code tries to have an abundance of caution. An assertion enforces the fact that the two keys are distinct and we explicitly add lifetimes to the returned variables.
You should understand the nuances of unsafe code before blindly using this solution.
Note that this function doesn't attempt to solve the original problem, which is vastly more complex than verifying that two indices are disjoint. The original problem requires:
HashMap in any way which would cause resizing, which would invalidate any of the existing references from a previous level.Using something like RefCell is a much simpler way to ensure you do not trigger memory unsafety.