I can do the following:
fn main() {
let vec = vec!["first", "last"];
println!("{}", vec.join(", "));
}
It gives this output:
first, last
If I try to use join with a map type, it fails:
error[E0599]: no method named
joinfound for typestd::collections::HashSet<&str>in the current scope
More efficiently, you can use itertools to join an iterator without collecting it into a Vec first:
extern crate itertools;
use std::collections::HashSet;
use itertools::Itertools;
fn main() {
let hash_set: HashSet<_> = ["first", "last"].iter().collect();
// Either of
println!("{}", hash_set.iter().join(", "));
println!("{}", itertools::join(&hash_set, ", "));
}
You can convert a HashSet into an Iterator, collect it and then use .join():
use std::collections::HashSet;
fn main() {
let mut books = HashSet::new();
books.insert("A Dance With Dragons");
books.insert("To Kill a Mockingbird");
books.insert("The Odyssey");
books.insert("The Great Gatsby");
println!("{}", books.into_iter().collect::<Vec<&str>>().join(", "));
}
You could do the same with a HashMap - you would just need to extract its .keys() or .values() first, depending on which you want to join.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With