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

kni*_*ght 6 rust

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

struct Context {
    lines: isize,
    buffer: Vec<String>,
    history: Vec<Box<Instruction>>,
}
Run Code Online (Sandbox Code Playgroud)

而功能,当然作为一种实现:

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 */ }
    }
}
Run Code Online (Sandbox Code Playgroud)

这不编译,我不明白错误信息.我在网上搜索类似的问题,我似乎无法在这里解决问题.我来自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
Run Code Online (Sandbox Code Playgroud)

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

Arj*_*jan 6

您从借用值self.historyget那借依然"活着"当你调用executeself(需要&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)
}
Run Code Online (Sandbox Code Playgroud)