代码之家  ›  专栏  ›  技术社区  ›  Kurtis Nusbaum

如何在匹配时不借用选项?

  •  2
  • Kurtis Nusbaum  · 技术社区  · 7 年前

    我有以下代码:

    fn remove_descendent(&mut self, key: &K) -> Option<V> {
        if self.left.is_some() && self.left.as_ref().unwrap().key == *key {
            return self.remove_left();
        }
    
        // more of the function
    }
    

    is_some 然后拆开包装。我想我真正应该做的是使用match语句来解构 Option left

    fn remove_descendent(&mut self, key: &K) -> Option<V> {
        match self.left {
            Some(ref left) if left.key == *key => self.remove_left(),
            _ => None
        }
    

    但是,执行此操作时会出现以下错误:

    error[E0502]: cannot borrow `*self` as mutable because `self.left.0` is also borrowed as immutable
      --> src/lib.rs:29:51
       |
    29 |             Some(ref left) if left.key == *key => self.remove_left(),
       |                  --------                         ^^^^ mutable borrow occurs here
       |                  |
       |                  immutable borrow occurs here
    30 |             _ => None
    31 |         }
       |         - immutable borrow ends here
    

    我想我明白我不能不可变地借用一个structs成员,然后可变地借用这个结构。但如果是这样的话,什么样的模式适合我 选择权 ? 有吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Tim Diekmann suresh madaparthi    7 年前

    编译器抱怨是因为在match arm中 self key 事先:

    fn remove_descendent(&mut self, key: &K) -> Option<V> {
        match self.left.clone() {
            Some(ref left) if left.key == *key => self.remove_left(),
            _ => None,
        }
    }
    

    你可以看到这个动作 on the Playground

    Non Lexical Lifetimes 启用后,您的代码编译得很好: Playground

    推荐文章