Join A Slice Into One String
Join a string slice into a separator-delimited String, convert numeric slices with map + to_string first, and see how empty and single-element slices behave.
Code
fn main() {
let fields = ["2026-11-19", "deploy", "api", "ok"];
// [&str]::join 用分隔符拼成单个 String
let csv = fields.join(",");
println!("csv: {csv}");
// 整数切片没有 join:[T]::join 只对元素本身是 &str/String 的切片成立,
// 数字必须先 map(to_string) 收集成 Vec<String> 再 join
let codes = [200, 404, 503];
let code_line = codes.iter().map(|c| c.to_string()).collect::<Vec<_>>().join(" / ");
println!("codes: {code_line}");
// 空切片 -> 空串;单元素 -> 无分隔符
let empty: [&str; 0] = [];
println!("empty join: {:?}", empty.join(","));
println!("single join: {:?}", ["only"].join(","));
// 拼回去:split 与 join 互逆
let roundtrip = csv.split(',').collect::<Vec<_>>().join(",");
println!("roundtrip equals csv: {}", roundtrip == csv);
}The mechanics
The code’s whole job belongs to the function main.
What to watch for
- No install step: all APIs used ship with the platform.
Putting it to use
Entry signature: fn main()
Step labels appear as — csv:, codes:, empty join: — when the file runs.
Lines that do the work
let code_line = codes.iter().map(|c| c.to_string()).collect::<Vec<_>>().join(" / ");
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Join A Slice Into One String print when run?
- Invoke the file as-is — the `csv:`, `codes:`, `empty join:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.