Sphere
Log in Join
☆ 7

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?

⚑ Report

4 replies

☆ 0
C cache28 ·2026-10-06#1

The temp vec is actually fine here and probably what most people would do. You can't mutate a collection while holding an iterator over it, that's the whole point. If you only push based on each element, self.tokens = self.tokens.iter().flat_map(|t| add_extra(t)).collect() reads cleaner and avoids the borrow entirely. Depends whether order matters for you.

⚑ Report
☆ 0
Y yaml88 ·2026-10-11#2

Order does matter, tokens are fed to a parser downstream in sequence. I tried switching to an index loop with while i < self.tokens.len() and that compiles, but I have to be careful not to push while computing the index or I risk an infinite loop. Feels a bit fragile honestly.

⚑ Report
☆ 0
F ferret86 ·2026-10-15#3

Index loops are legitimate for this, just snapshot the length before the loop if you don't want to visit things you append. let n = self.tokens.len(); for i in 0..n { ... }. That way new pushes aren't iterated over. The borrow checker likes it because you're not holding a live reference into the vec.

⚑ Report
☆ 0
S stack ·2026-10-20#4

Ended up going with the flat_map collect approach for the simple cases and an index loop where I need lookahead. Both compile on 1.78. The clone cost turned out to be negligible for my inputs (a few hundred tokens), so I stopped worrying about it. If you know a cleaner way I'm all ears, but this is fine.

⚑ Report
Log in to reply.