不能把`* self`借给可变,因为`self.history [..]`也被借用为不可变的`

时间:2014-04-12 15:37:01

标签: rust

代码类似于以下内容,在函数中是Context结构的实现,定义如下:

struct Context {
    lines: isize,
    buffer: Vec<String>,
    history: Vec<Box<Instruction>>,
}

这个功能当然是一个实现:

fn _execute_history(&mut self, instruction: &Instruction) -> Reaction {
    let num = instruction.suffix.parse::<usize>();
    match num {
        Ok(number) => {
            match self.history.get(number) {
                Some(ins) => { return self.execute(*ins); },
                _         => { /* Error handling */ }
            }
        }
        Err(..) => { /* Error handling */ }
    }
}

这不编译,我不明白错误信息。我在网上搜索类似的问题,我似乎无法在这里解决问题。我来自Python背景。完整错误:

hello.rs:72:23: 72:35 note: previous borrow of `self.history[..]` occurs here; the immutable
borrow prevents subsequent moves or mutable borrows of `self.history[..]` until the borrow ends

我完全清楚该函数不符合类型系统,但这是因为简化代码仅用于演示目的。

1 个答案:

答案 0 :(得分:6)

您从self.history借用了get的值,当您在execute上呼叫self时,借用仍为“有效”(需要&mut self来自self.execute我从错误中可以看到的内容)

在这种情况下,请从匹配项中返回您的值,并在匹配后调用fn _execute_history(&mut self, instruction: &Instruction) -> Reaction { let num = instruction.suffix.parse::<usize>(); let ins = match num { Ok(number) => { match self.history.get(number) { Some(ins) => ins.clone(), _ => { /* Error handling */ panic!() } } } Err(..) => { /* Error handling */ panic!() } }; self.execute(ins) }

{{1}}