Why isn't this rust code working

Hello. I'm learning Rust, and I'm making a super-mini interpreter (mostly).
However, I get this error:

cannot borrow self.lexer as mutable more than once at a time
second mutable borrow occurs here
parser.rs(39, 30): first mutable borrow occurs here
parser.rs(17, 6): lifetime 'a defined here
parser.rs(39, 30): returning this value requires that *self is borrowed for 'a

Edit: Playground of the code

It is hard to help you without having the complete code or at least the line numbers. The complete error message should includes the offending code. You can paste the code to play.rust-lang.org.

In general a function with the signature fn name(&'a mut self) -> T<'a> will mutably borrow self as long as the return value is alive. What lifetime does 'a denote in your code?

It is almost always wrong to have an explicit lifetime parameter on self.

Given that your other parser function returns a type with lifetime 'a independent of the lifetime of self, you should probably do the same in your second method and simply remove the 'a requirement from self.

1 Like

That doesn't help though. I added the &'a mut self because rust suggested to fix the issue, but it didn't :frowning:

Don't pay attention to compiler suggestions, they are almost never correct (except in the most trivial case), and especially not when it comes to lifetimes.

Also, please add complete code that compiles except for the error you are trying to resolve. I have no idea how Lexer is defined, for example.

Thanks, but I managed to resolve it. The spam detector flagged this post, so it got hidden for some time. I change many things, like I change 'a to 'static, nothing worked
when, finally after 2 hours of searching, I managed to resolve it.

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.