borrow checker won't let me push to a vec while iterating it
rustc 1.78.0 here, writing a tiny tokenizer for a side project. I have a struct with tokens: Vec<String> and a method that walks the tokens and wants to append a synthesized one when it sees a certain pattern. I keep getting:
error[E0502]: cannot borrow self.tokens as mutable because it is also borrowed as immutable
--> src/lexer.rs:58:13
|
57 | for tok in &self.tokens {
| ------------ immutable borrow occurs here
58 | self.tokens.push(tok.clone());
| ^^^^^^^^^^^^^^ mutable borrow occurs here
Collecting into a temp vec first works but feels like a waste. What's the idiomatic way to do this without cloning everything?
4 replies