Vec map / collect / capacity

โš“ Rust    ๐Ÿ“… 2025-12-14    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 9      

surdeus

Warning

This post was published 34 days ago. The information described in this article may have changed.

Does

  let my_new_vector: Vec<foo> my_vector.iter().map(..elided..).collect();

preallocate the length of my_new_vector?

If not, I suppose I could write it out manually using a for loop

There is a proposal ([Tracking Issue for `Iterator::collect_into` ยท Issue #94780 ยท rust-lang/rust ยท GitHub]) that
seems to address this (using method 'collect_into'), but it's not currently in stable.

I am confused since there was a bug in the last year or so roughly about
iter/map/collect reusing the vector but not cleaning up excess space, which
implies some sort of reuse (note 1). I have done some googling but have
not found chapter-and-verse that answers this (fair enough, if collect_into
becomes stable, that's the 'best answer' for what I am trying to do).

Note 1: I don't know if I want reuse or not. Situation is build a vector of
preparation elements, then build the final result in the map/collect.

5 posts - 4 participants

Read full topic

๐Ÿท๏ธ Rust_feed