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.

RustCli Tooling

Code

rustsnippet
22 lines
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

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.