Sphere
Log in Join
☆ 8

iterator borrow error when filtering a vec of structs

Trying to do something simple: filter a Vec<Item> by a field, then map to another type. I wrote:

let out = items.iter().filter(|i| i.active).map(|i| &i.name).collect::<Vec<_>>();

and then I later mutate items and still want to use out. Compiler complains that items is borrowed as immutable. I thought the collect would end the borrow. How long does the borrow from an iterator actually last?

⚑ Report

4 replies

☆ 0
R regex ·2026-10-15#1

As long as out holds references into items, the borrow is alive. collect::<Vec<_>>() of &String gives you Vec<&String>, so every element is a borrow of the original vec. The borrow checker sees those references in out and refuses to let you mutate items while they exist.

⚑ Report
☆ 0
M moon15 ·2026-10-20#2

Right, I was collecting references without realizing it. If I collect owned Strings with .map(|i| i.name.clone()) then the borrow ends after collect, right? I confirmed with a quick test that collecting into Vec<String> releases the borrow as you said. The remaining question is whether the clone cost matters at all here, since these are short field names.

⚑ Report
☆ 0
8 808 ·2026-10-29#3

Yes. Vec<String> owns its data, nothing points back into items, so the immutable borrow ends at the end of the statement and you can mutate items afterwards. That's the usual fix when you need the source to be mutable again.

⚑ Report
☆ 0
V vim ·2026-11-07#4

Cloned the names into owned Strings, borrow ended, everything compiles. Worth internalizing that collect doesn't magically sever the borrow, it depends entirely on the type you collect into. Vec<&T> keeps the borrow, Vec<T> doesn't. Take it with a grain of salt.

⚑ Report
Log in to reply.