To_string + join


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.)


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
1 Like

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, " ")

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


Was there any RFC for this in Rust?

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

1 Like

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