【问题标题】:Why do I get the error "cannot borrow x as mutable more than once"?为什么我会收到错误“不能多次借用 x 作为可变变量”?
【发布时间】:2016-01-13 00:19:46
【问题描述】:

我正在用 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();
}

【问题讨论】:

    标签: rust lifetime


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 在 rust 中做这样的事情的正确方法是什么?
      • @GOD 重组你的代码,这样你就不会持有对正在变异的东西的引用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-26
      相关资源
      最近更新 更多