How to fix this ‘second mutable borrow occurs here’ error

I came up with

    fn search(&mut self, elem: &T) -> Result<&mut Link<T>, &mut Link<T>> {
        let mut link = &mut self.root;
        while let Some(ref node) = link {
            match elem.cmp(&node.elem) {
                std::cmp::Ordering::Less => link = &mut link.as_mut().unwrap().left,
                std::cmp::Ordering::Greater => link = &mut link.as_mut().unwrap().right,
                _ => return Ok(link),
            }
        }

        Err(link)
    }

which seems to work?

2 Likes