Reputation: 12459
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
join
found for typestd::collections::HashSet<&str>
in the current scope
Upvotes: 9
Views: 5117
Reputation: 431689
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, ", "));
}
Upvotes: 9
Reputation: 22273
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.
Upvotes: 9