【问题标题】:Cannot borrow `*self` as mutable because `self.history[..]` is also borrowed as immutable不能将 `*self` 作为可变借用,因为 `self.history[..]` 也作为不可变借用
【发布时间】:2014-04-12 15:37:01
【问题描述】:

代码类似于以下,在一个函数中,它是 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

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

【问题讨论】:

    标签: rust


    【解决方案1】:

    您使用 getself.history 借用一个值,并且当您在 self 上调用 execute 时,该借用仍然“有效”(从错误中我可以看到,这需要 &amp;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)
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      相关资源
      最近更新 更多