如何使用分隔符将 HashSet 的元素连接到字符串中 [英] How to join elements of HashSet into a String with a delimiter
本文介绍了如何使用分隔符将 HashSet 的元素连接到字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以执行以下操作:
fn main() {
let vec = vec!["first", "last"];
println!("{}", vec.join(", "));
}
它给出了这个输出:
第一个,最后一个
如果我尝试将 join
与地图类型一起使用,它会失败:
If I try to use join
with a map type, it fails:
error[E0599]: 在当前作用域中没有为 std::collections::HashSet<&str>
类型找到名为 join
的方法
error[E0599]: no method named
join
found for typestd::collections::HashSet<&str>
in the current scope
推荐答案
更高效,您可以使用 itertools 先加入一个迭代器而不将它收集到 Vec
中:
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, ", "));
}
这篇关于如何使用分隔符将 HashSet 的元素连接到字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文