为什么我会收到错误 "cannot borrow x as mutable more than once"?

Why do I get the error "cannot borrow x as mutable more than once"?

我正在用 Rust 实现一个解析器。我必须为前瞻更新索引,但是当我在 self.current() 之后调用 self.get() 时,我得到一个错误:

cannot borrow *self as mutable more than once at a time

因为我是 Rust 的新手,所以很困惑。

#[derive(Debug)]
pub enum Token {
    Random(String),
    Undefined(String),
}

struct Point {
    token: Vec<Token>,
    look: usize,
}

impl Point {
    pub fn init(&mut self){
        while let Some(token) = self.current(){
            println!("{:?}", token); 
            let _ = self.get();
        }
    }

    pub fn current(&mut self) -> Option<&Token> {
        self.token.get(self.look)
    }

    pub fn get(&mut self) -> Option<&Token> {
        let v = self.token.get(self.look);
        self.look += 1;
        v
    }

}

fn main(){
    let token_list = vec![Token::Undefined("test".to_string()),
                     Token::Random("test".to_string())];

    let mut o = Point{ token: token_list, look: 0 };
    o.init();
}

函数Point::get改变了它被调用的Point。函数 Point::current returns 对调用它的 Point 的一部分的引用。所以,当你写

while let Some(token) = self.current() {
    println!("{:?}", token); 
    let _ = self.get();
}

token 是对存储在 self 中的内容的引用。因为改变 self 可能会更改或删除 token 指向的任何内容,编译器会阻止您在变量 token 处于范围内时调用 self.get()

@Adrian 已经给出了编译器给出错误消息的正确原因。如果将变异表达式绑定在一个范围内,然后在范围完成后调用 self.get,则可以编译程序。
代码可以修改为

loop{
    {
        let t = if let Some(token) = self.current(){
                    token
                }else{
                    break
                };
        println!("{:?}", t); 
    }
    let b = self.get();
    println!("{:?}", b);
}