不能借用 `*self` 作为可变的,因为 `self.history[..]` 也被借用为不可变的 [英] Cannot borrow `*self` as mutable because `self.history[..]` is also borrowed as immutable

查看:34
本文介绍了不能借用 `*self` 作为可变的,因为 `self.history[..]` 也被借用为不可变的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The code is something like the following, in a function that is an implementation for a Context struct, defined as the following:

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

和函数,当然是作为一个实现:

And the function, of course as an implementation:

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 背景.完整的错误:

This doesn't compile and I don't understand the error message. I searched online for similar problems and I cannot seem to grasp the problem here. I am from a Python background. The full error:

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

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

I am fully aware that the function is not conforming to the type system, but this is because the simplified code is for demonstrative purposes only.

推荐答案

您使用 getself.history 借用一个值,并且该借用仍然活着"你在 self 上调用 execute (这需要 &mut self 从我从错误中看到的)

You borrow a value from self.history with get and that borrow is still "alive" when you call execute on self (that requires &mut self from what I can see from the error)

在这种情况下,从匹配中返回您的值并在匹配后调用 self.execute:

In this case return your value from the match and call self.execute after the match:

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)
}

这篇关于不能借用 `*self` 作为可变的,因为 `self.history[..]` 也被借用为不可变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆