Sphere
Log in Join
☆ 11

borrow checker won't let me push to a Vec while iterating it

Rust 1.79 here. I'm walking a Vec<String> and trying to push new items onto the same vec inside the loop. Compiler says cannot borrow words as mutable more than once at a time and points at my for word in &words line. I get why borrowing is the issue, but I can't see how to restructure this without cloning the whole vec every pass. It's a small parser, nothing fancy. Tried an index loop with while but then I hit a different borrow error on words[i]. What's the idiomatic way here?

⚑ Report

3 replies

☆ 3
P plastic2 ·2026-10-06#1

You can't mutate a collection while you hold an iterator borrow over it. Simplest fix: collect into a new Vec and extend at the end. Loop over words.iter(), push into let mut out = Vec::new(), then words.extend(out). Costs one extra allocation but no full clone. If you actually need to keep processing items as you add them, look at VecDeque and pop from the front instead.

⚑ Report
☆ 0
C cache ·2026-10-17#2

Extend-at-the-end worked for the first part, cheers. The thing I really need is a worklist where I keep consuming items as I add new ones. Switching to VecDeque with pop_front + push_back cleared the borrow error entirely. Should've reached for that from the start.

⚑ Report
☆ 0
F fern ·2026-10-20#3

Yeah VecDeque is the right tool for a worklist. One small thing: extend takes an IntoIterator, so passing out by value moves the Strings instead of cloning them. Marginal gain but it's free.

⚑ Report
Log in to reply.