重组匹配语句以满足借阅检查器

时间:2019-04-01 02:10:42

标签: rust lifetime borrow-checker

我正在尝试编写一个trie结构,该结构吸收字符流并将它们添加到trie(如果尚不存在)。添加字符后,它将返回顶部以再次开始。

#[derive(Debug)]
pub struct Trie {
    char: u8,
    children: [Option<Box<Self>>; 2],
}

impl Trie {
    pub fn new(char: u8) -> Trie {
        return Trie {
            char,
            children: [None, None],
        };
    }

    pub fn push(&mut self, lz_pair: Trie) {
        let idx = lz_pair.char as usize;
        self.children[idx] = Some(Box::new(lz_pair));
    }

    pub fn get_child(&mut self, char: u8) -> Option<&mut Trie> {
        let child = self.children[char as usize].as_mut();
        if let Some(c) = child {
            Some(c.as_mut())
        } else {
            None
        }
    }
}

fn main() {
    let data = b"abbabababbbbbabaaaabababaa";

    let mut root = Trie::new(0);
    let mut cur = &mut root;

    for c in data {
        cur = match cur.get_child(*c) {
            Some(child) => child,
            None => {
                cur.push(Trie::new(*c - 97));
                &mut root
            }
        };
    }
}

Playground

实际的代码要复杂一些,但是我将其精炼为仅显示此错误。

借阅检查员抱怨:

error[E0499]: cannot borrow `*cur` as mutable more than once at a time
  --> src/main.rs:40:17
   |
37 |         cur = match cur.get_child(*c) {
   |                     --- first mutable borrow occurs here
...
40 |                 cur.push(Trie::new(*c - 97));
   |                 ^^^
   |                 |
   |                 second mutable borrow occurs here
   |                 first borrow used here, in later iteration of loop

在解开Option(即This question and all the duplicates)时,我已经阅读了有关借位检查器错误的所有问题,因此我有点理解为什么会发生,但是我不知道如何可以重组此代码来解决这种特殊情况。

在我使用2018版本的Rust进行编译时,非词法生命周期似乎无法解决此问题。

0 个答案:

没有答案