Converting a Vec to a string of comma separated values

Hi,

Which is the most idiomatic way to convert a Vec of objects (assuming that they implement ToString trait) to a sequence of strings comma separated?

Thank you.

P.S.:
Using stable Rust, so cannot use (so far) intersperse

Hi,

vec.iter().map(|x| x.to_string() + ",").collect::<String>()

That will contain a trailing ','

If the elements implement Borrow<str>, then you can use the join method:

fn comma_separated(v: Vec<String>) -> String {
    v.join(",")
}

Playground

Or you can use the itertools crate, which has a more general join method as well as a version of intersperse that works on stable Rust.

7 Likes
let string = vec.iter().map(|x| x.to_string() + ",").collect::<String>();
let string = string.trim_end_matches(",");

I usually do

vec.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(",");

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.