0

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.

1 Answer 1

2

AFAIK, your work around is good and sound without non-std libs.

Several cargos provide some helper functions for this issue, for example:

Playground

itertools and joinery

use itertools::Itertools;
use joinery::Joinable;

struct Color {
    red: u8,
    green: u8,
    blue: u8,
}

impl std::fmt::Display for Color {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "RGB ({}, {}, {}) 0x{:02X}{:02X}{:02X}",
            self.red, self.green, self.blue, self.red, self.green, self.blue
        )
    }
}

fn main() {
    let colors = vec![
        Color {
            red: 128,
            green: 255,
            blue: 90,
        },
        Color {
            red: 0,
            green: 3,
            blue: 254,
        },
    ];

    println!(
        "{}",
        colors
            .iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(", ")
    );

    println!("{}", colors.iter().join(", "));
    println!("{}", colors.join_with(", "));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.