slice::join¶
Level: reference · for working programmers
One line: Flatten a slice of slices or strings into one, with a separator between the pieces.
pub fn join<Separator>(&self, sep: Separator) -> <[T] as Join<Separator>>::Output
where
[T]: Join<Separator>,
Stable since 1.3.0.
["red", "green", "blue"].join(", ") is "red, green, blue" — the method Python spells ", ".join(parts), with the separator and the pieces the other way round. Works on [&str] and [String] alike; join("") is concat.
It is not only for strings. A slice of slices joins with an element or a slice as the separator: rows.join(&0) puts one 0 between each row, rows.join(&[0, 0][..]) puts two.
Numbers have no join. [1, 2, 3].join(",") is error[E0599]: the method needs pieces that are themselves slices or strings. Map to strings first — nums.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(",") — which is the idiom for building any comma-separated line.
An empty slice joins to an empty string, with no separator anywhere.
Example¶
slice_join.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let words = ["red", "green", "blue"];
println!("{}", words.join(", "));
println!("{} <- join(\"\") is concat", words.join(""));
let owned = vec![String::from("a"), String::from("b")];
println!("{}", owned.join("-"));
// Not only strings: slices of slices, with an element or a slice between.
let rows = [vec![1, 2], vec![3, 4]];
println!("{:?}", rows.join(&0));
println!("{:?}", rows.join(&[0, 0][..]));
// Numbers have no join — [1, 2, 3].join(",") is error[E0599]. Map to strings first.
let nums = [1, 2, 3];
let csv = nums.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(",");
println!("{csv}");
// An empty slice joins to an empty string.
let none: [&str; 0] = [];
println!("{:?}", none.join(", "));
}
Verified output of slice_join.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
slice::concat— no separatorslice::iter—map(to_string)before a join over numbers