模式匹配 - 生锈:"cannot move out of `self` because it is borrowed"错误



我正在尝试编写一个递归方法,将一个项添加到树中,并返回与该项对应的树节点。

enum BstNode {
    Node(int, ~BstNode, ~BstNode),
    Leaf
}
impl BstNode {
    fn insert<'a>(&'a mut self, item: int) -> &'a mut BstNode {
        match *self {
            Leaf => {
                *self = Node(item, ~Leaf, ~Leaf);
                self
            },
            Node(ref node_item, ref mut left, ref mut right) =>
                match item.cmp(node_item) {
                    Less => left.insert(item),
                    Equal => self,
                    Greater => right.insert(item)
                }
        }
    }
}

我被以下错误所困扰:

bst.rs:19:30: 19:34 error: cannot move out of `self` because it is borrowed
bst.rs:19                     Equal => self,
                                       ^~~~
bst.rs:16:18: 16:31 note: borrow of `self#0` occurs here
bst.rs:16             Node(ref node_item, ref mut left, ref mut right) =>
                           ^~~~~~~~~~~~~

"搬出something"是什么意思?如何修复此错误?

我使用的是Rust 0.10。

在示例node_item中,leftrightself变量所有。在的Equal分支中,借款检查器不知道这一点

match item.cmp(node_item) {
    Less => left.insert(item),
    Equal => self,
    Greater => right.insert(item)
}

node_itemleftright都没有使用,但它看到self正在移动(您正在返回它),而这三个变量仍然被借用(您仍然在匹配的词法范围内,它们被借用)。我认为这是一个已知的错误,即这种行为过于严格,请参阅问题#6993。

至于修复代码的最佳方法,老实说,我不确定。我会使用一个完全不同的结构(至少在修复之前):

pub struct BstNode {
  item: int,
  left: Option<~BstNode>,
  right: Option<~BstNode>
}
impl BstNode {
    pub fn insert<'a>(&'a mut self, item: int) -> &'a mut BstNode {
        match item.cmp(&self.item) {
            Less => match self.left {
              Some(ref mut lnode) => lnode.insert(item),
              None => {
                self.left = Some(~BstNode {item: item, left: None, right: None});
                &mut **self.left.as_mut().unwrap()
              }
            },
            Equal => self,
            Greater => match self.right {
              Some(ref mut rnode) => rnode.insert(item),
              None => {
                self.right = Some(~BstNode {item: item, left: None, right: None});
                &mut **self.right.as_mut().unwrap()
              }
            }
        }
    }
}

这样,当您返回节点时,它的任何成员都不会被借用。

相关内容

最新更新