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

社会主义新天地 提交于 2019-12-02 03:55:01

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 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.

@Adrian already gave the correct reason for why the compiler is giving the error message. If you bound the mutating expressions within a scope and then call self.get after the scope completion, you can compile the program.
The code can be modified as

loop{
    {
        let t = if let Some(token) = self.current(){
                    token
                }else{
                    break
                };
        println!("{:?}", t); 
    }
    let b = self.get();
    println!("{:?}", b);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!