rust - 匹配时如何不借用期权?

标签 rust

我有以下代码:

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 语句来解构由 left 变量表示的 Option,如下所示:

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

我想我明白我不能一成不变地借用结构成员,然后可变地借用该结构。但如果是这样的话,模式匹配我的 Option 的正确方法是什么?有吗?

最佳答案

编译器会提示,因为在匹配中,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 .

关于rust - 匹配时如何不借用期权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50752778/

相关文章:

rust - 从 Option<Rc<RefCell<T>>> 解包并访问 T

rust - 我可以在 Rust 中定义我自己的 "strong"类型别名吗?

rust - UFCS:解析 T::方法

rust - 默认发布版本是否始终使用 SSSE3 指令?

rust - 当函数引用变量作为参数时,函数的堆栈到底分配了什么?

rust - "does not necessarily outlive the lifetime"问题

rust - 创建静态常量 Vec<String>

indexing - 如何将范围作为 Rust 中的变量?

rust - 如何绘制范围?

generics - 如何将 "Encodable"绑定(bind)到类型参数?