What is the equivalent of the join operator over a vector of Strings?
我无法在
1 2 3 | let string_list = vec!["Foo".to_string(),"Bar".to_string()]; let joined = something::join(string_list,"-"); assert_eq!("Foo-Bar", joined); |
有关:
- 在Rust中用空格分隔打印迭代器的惯用方式是什么?
在Rust 1.3.0和更高版本中,
1 2 3 4 5 | fn main() { let string_list = vec!["Foo".to_string(),"Bar".to_string()]; let joined = string_list.join("-"); assert_eq!("Foo-Bar", joined); } |
在1.3.0之前,此方法称为
1 | let joined = string_list.connect("-"); |
请注意,您不需要导入任何内容,因为方法是由标准库序言自动导入的。
正如威尔弗雷德(Wilfred)所述,自版本1.3.0起,已不推荐使用
1 | let joined = string_list.join("-"); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | extern crate itertools; // 0.7.8 use itertools::free::join; use std::fmt; pub struct MyScores { scores: Vec<i16>, } impl fmt::Display for MyScores { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str("MyScores(")?; fmt.write_str(&join(&self.scores[..], &","))?; fmt.write_str(")")?; Ok(()) } } fn main() { let my_scores = MyScores { scores: vec![12, 23, 34, 45], }; println!("{}", my_scores); // outputs MyScores(12,23,34,45) } |