字符串向量上的连接运算符等价于什么?

我无法在Strings的向量上找到“join”操作符的Rust等价。我有一个Vec<String>,我想将它们作为一个单独的String加入:

let string_list = vec!["Foo".to_string(),"Bar".to_string()];
let joined = something::join(string_list,"-");
assert_eq!("Foo-Bar", joined);

相关:

151195 次浏览

在Rust 1.3.0及以后版本中,join可用:

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之前,这个方法被称为connect:

let joined = string_list.connect("-");

注意,你不需要导入任何东西,因为方法是由标准库前奏自动导入的。

正如Wilfred所提到的,SliceConcatExt::connect自1.3.0版本以来已被弃用,取而代之的是SliceConcatExt::join:

let joined = string_list.join("-");

itertools板条箱中有一个函数也称为join,它连接一个迭代器:

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)
}