How do I convert an Iterator
<&str>
to a String
, interspersed with a constant string such as "\n"
?
For instance, given:
let xs = vec!["first", "second", "third"];
let it = xs.iter();
One may produce a string s
by collect
ing into a Vec<&str>
and join
ing the result:
let s = it
.map(|&x| x)
.collect::<Vec<&str>>()
.join("\n");
However, this unnecessarily allocates memory for a Vec<&str>
.
Is there a more direct method?
itertools
crate doesn't allocate the vector – Feminizeitertools
, sinceSliceConcatExt::join
can calculate the needed size for the full string ahead of time and thus definitely doesn't need to reallocate during accumulation; whereas the other methods may have to reallocate the string. You should definitely benchmark. – Phenocrystcollect::<Vec<&str>>
would need to reallocate, but it's a lot smaller than the string buffer, so i guess that would be a faster? – Sakeonce
plusskip
trick works nicely for this. See also this answer. – Polybasite.map(|&x| x)
part... why is that? – Selfmade