string 字符串向量上的连接运算符的等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28311868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the equivalent of the join operator over a vector of Strings?
提问by Davide Aversa
I wasn't able to find the Rust equivalent for the "join" operator over a vector of String
s. I have a Vec<String>
and I'd like to join them as a single String
:
我无法在String
s向量上找到“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);
Related:
有关的:
回答by MatthewG
In Rust 1.3.0 and later, join
is available:
在 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);
}
Before 1.3.0 you can use connect
:
在 1.3.0 之前,您可以使用connect
:
let joined = string_list.connect("-");
Note that you do not need any imports as the methods are automatically imported by the standard library prelude.
请注意,您不需要任何导入,因为标准库 prelude会自动导入这些方法。
回答by Danilo Bargen
As mentioned by Wilfred, SliceConcatExt::connect
has been deprecated since version 1.3.0 in favour of SliceConcatExt::join
:
正如 Wilfred 所提到的,SliceConcatExt::connect
自 1.3.0 版以来已被弃用,取而代之的是SliceConcatExt::join
:
let joined = string_list.join("-");
回答by Nick Linker
There is a function from the itertools
crate also called join
which joins an iterator:
来自itertools
crate 的一个函数也被调用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)
}