Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

rust - Cannot borrow `*self` as mutable because `self.history[..]` is also borrowed as immutable

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 */ }
    }
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...