Join method for all iterators


So I have recently had a situation where i had an iterator over String, and I wanted to join them with a space in the middle. it turned out to be really awkward.

I was surprised to be unable to find a join method on the iterator that did the job. I did find std::slice::SliceConcatExt But that seems to be rather specific on slices, and I didn’t want to make one.

Rather than solve the problem for my specific case, I remembered that Premature Generalization is the root of all Evil, and so of course that’s what I did.

The above is a joining iterator trait called Joinable which works on almost anything. It clones and repeats the joining parameyer and alternates with the original iterator starting and ending with values from the original iterator.

Could this / or something like it have a place in the stdlib?


I agree it’s a missing functionality. There were many occasions when I wished to have join() on an iterator of strings.

I was thinking about implementing a collect-like method on Iterator of elements like AsRef<str> or Display.

Your solution is interesting. It doesn’t actually do the joining, but it’s more like interleaving.


I think the itertools crate already has a join method: Seems like IntoIterator is good enough for it, so I’m not sure a new Joinable trait buys us anything.


yeah, I pondered writing using some actual form of interleave on two separate iterators and then making this a specific case,where the iterator returns the same thing.

I think that might have been too generalized even for me.


ah, that’s what I was looking for lol. Coulda saved me some work there. I probably wouldn’t have bothered writing this if i’d found that first.

Still: this version chains on iterators, so that might still have value.

Maybe I’ll make it a crate instead.


I’m not sure I would call your function on the playground “join”. If I understand correctly, it turns

["hello", "world", "and", "goodnight"]


["hello", ",", "world", ",", "and", ",", "goodnight"]

, right? This sounds like Itertools::intersperse.


yup it sounds exactly like that. and looking at the code it does the job better too.