Joining a Iterator of String/&str

#1
  1. Suppose it is an iterator over String or &str, we can do something like:
let ans: Vec<String> = ans.collect();
ans.join(" ");
  1. Now, I’m wondering if it’s possible to join on the iterator directly, without first collecting it into a Vec<String>
1 Like
#2

You can with itertools:
https://docs.rs/itertools/0.8.0/itertools/trait.Itertools.html#method.join

5 Likes
#3

Note that join on slices is more efficient than Itertools::join, because it can pre-calculate the amount of memory that the final result will need and forgo bounds checking in the copy loop as a result. You can’t do that with an Iterator, which is why the standard library’s join is defined only for slices and not for any iterator.

4 Likes