0

I ran into a weird compiling error about borrowing and cannot figure it out, the codes are like this:

pub struct Lexer<'a> {
    input: String,
    token: Token<'a>,
}

#[derive(Debug, Copy, Clone)]
pub struct Token<'a> {
    pub t: i32,
    pub literal: &'a str,
}

impl<'t, 'l : 't> Lexer<'t> {
    pub fn next_token(&'l mut self) {
        // compiler error info says -> "`self.token` is borrowed here"
        self.read_number(); 
        
        /* -----------  ERROR ---------------------
        cannot assign to `self.token` because it is borrowed
`self.token` is assigned to here but it was already borrowed
         --------------------------------------------------
        */
        self.token = Token {t : 10, literal: "abc"};
    }
    
    fn read_number(&'l mut self)  {
    }
}

I cannot get it. Function read_number is just a trivial empty function how can it borrow the self.token? Does it have something to do with the argument &'l mut self?

hliu
  • 1,015
  • 8
  • 16
  • `&'l mut self` is wrong. If I would have to guess why you did that, I would guess because you're trying to create a self-referential struct, but there is no evidence in the code so I cannot say for sure. – Chayim Friedman Jun 11 '23 at 12:09
  • @ChayimFriedman Yes. I have simplified the code for clear. The struct `Token` own a slice referring to the origin input string. Could you please give some more hint of how the `&'l mut self` leads to the borrowing of self.token, i'm really confused. Thanks a lot. – hliu Jun 11 '23 at 12:16
  • `&'l mut self` leads to the borrowing of the whole `self`. `self.token` included. – Cerberus Jun 11 '23 at 15:36

0 Answers0