为什么会出现错误“不能多次借用x作为可变变量"? [英] Why do I get the error "cannot borrow x as mutable more than once"?

查看:56
本文介绍了为什么会出现错误“不能多次借用x作为可变变量"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm implementing a parser in Rust. I have to update the index for the lookahead, but when I call self.get() after self.current() I get an error:

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

由于我是Rust的新手,这很令人困惑.

It's confusing since I'm new to 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返回对其调用的Point部分的引用.所以,当你写

The function Point::get mutates the Point that it is called on. The function Point::current returns a reference to a part of the Point that it is called on. So, when you write

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

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

token is a reference to something stored in self. Because mutating self might change or delete whatever token points to, the compiler prevents you from calling self.get() while the variable token is in scope.

这篇关于为什么会出现错误“不能多次借用x作为可变变量"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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