0

I am storing bunch of items in BTreeMap and I am querying for keys as mutable in a range. If nothing is found in that range, I want to return the first value in map as mutable. Idea is doing something like cycle() but without copying. In my implementation however, I am running into rust borrow check issues. So My question is why I am running into borrow check when clearly I only want one mutable borrow and secondly how do I fix this?

impl<'a> ConsistentHash {
    fn select(&'a mut self, key: &str) -> Option<&'a mut MemoryNode> {
        if self.nodes.is_empty() {
            return None;
        }

        let hash = calculate_hash(&key);

        {
            if let Some(v) = self.nodes
                .range_mut((Included(hash), Included(u64::MAX)))
                .next() {
                return Some(v.1);
            }
        }


        return self.nodes.values_mut().next()

    }

here self.nodes is BTreeMap. Upon compiling this, I run into following error

  if let Some(v) = self.nodes
   |  ______________________________-
46 | |                 .range_mut((Included(hash), Included(u64::MAX)))
   | |________________________________________________________________- first mutable borrow occurs here
47 |                   .next() {
48 |                   return Some(v.1);
   |                          --------- returning this value requires that `self.nodes` is borrowed for `'a`
...
53 |           return self.nodes.values_mut().next()
   |                  ^^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
Sigma
  • 742
  • 2
  • 9
  • 24

0 Answers0