I have a type T that implements display (so it has a .to_string() method)
let my_vec = vec![T(), T(), T()];
println!("{}", my_vec.join(", "));
sadly errors with "trait bounds not satisfied" because the separator, ", ", is not of the same type as the vector's items (I'm pretty sure).
I guess my workaround is then
println!("{}", my_vec.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", "));
But isn't there anything shorter and clearer that I can write out instead of this?
I've just written this function to help me out:
fn join<T, I>(vec: &[T], sep: I) -> String
where
T: std::fmt::Display,
I: std::fmt::Display,
{
vec.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(&sep.to_string())
}
But I'd rather not have to. There must be alternative solutions that: are already built-in, don't require manual implementation, at least don't require the creation of a top-level function that's then only called twice.