To_string + join

#1

The following code works:

        let sks = self.keys.iter().map(|x| { x.to_string() }).collect::<Vec<_>>();
        let mut msg = sks.join(" ");

I find it a bit ugly in that we construct a temporary Vec just to call join on it. Is there a simpler way to do this (besides running a for loop and manually appending to the string.)

#2

Assuming that keys contain &str:

let mut sks = self.keys.iter().fold(String::new(), |a, x| a + x + " ");
let n = sks.len();
if n > 0 { sks.truncate(n - 1); }
// or if you want to show-off
sks.truncate(sks.len().wrapping_sub(1));
1 Like
#3

With itertools you can write:

use itertools::Itertools;
let msg = self.keys.iter().join(" ");

Or use the standalone function:

let msg = itertools::join(&self.keys, " ")
3 Likes
#4

You could also just String::pop the last char instead of using String::truncate

3 Likes
#5

Was there any RFC for this in Rust?

I remember it was discussed previously and ended up being something like Iterator::intersperse

1 Like
#6

Is Connecting (joining) string slices without a temp Vec the thread you’re referring to?