Borrowed assignment in while loop

pub struct Lexer {
    source: String,
    cursor: u64
}
impl Lexer {
    pub fn tokenize(&mut self) -> Vec<YamlToken> {
        let mut tokens: Vec<YamlToken> = vec![];

        while self.cursor < self.source.len() as u64 {
            self.cursor += 1;
            // Other logic here
        }
        return tokens;
    }
}

I just want to increment the cursor at the start of every iteration. How could I do that without running into the issue of assigning to a borrrowed value?

The code you posted compiles without any errors. I imagine in your actual code you call self.current() and push the result of the call into tokens in some way, which causes &self to be borrowed for the rest of tokenize. One easy way to fix it would be to make current take a &str and u64 instead and call it with (&self.source, self.cursor) so the cursor field doesn't get borrowed.

1 Like

Thank you for the help. Unfortunately, this doesn't seem to fix the issue.

Like @Heliozoa pointed out, your example (when adding a simple placeholder for YamlToken), compiles on the playground:

pub struct YamlToken;

pub struct Lexer {
    source: String,
    cursor: u64
}

impl Lexer {
    pub fn tokenize(&mut self) -> Vec<YamlToken> {
        let mut tokens: Vec<YamlToken> = vec![];

        while self.cursor < self.source.len() as u64 {
            self.cursor += 1;
            // Other logic here
        }
        return tokens;
    }
}

so your error must arise in here somewhere:

Also, the full error message you see in your console would be helpful.

2 Likes

Friendly reminder unrelated to the borrowing problem at hand: As you are iterating over byte indices of a String, make sure to test whether your code behaves as intended with non-ASCII input, too :slight_smile:

Thanks for the reminder but I do enforce that with a function.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.