Join Iterator Elements With Separator

Flatten a collection into one String with join, which works on slices of str, String, and even Option values, without hand-rolled loops or format! chains.

RustData Integrity

Code

rustsnippet
19 lines
fn main() {
    let hosts = ["api.example.com", "cdn.example.com", "static.example.net"];

    // &[&str] 直接 join:借用元素,零多余拷贝
    let header = hosts.join(", ");
    println!("hosts: {header}");

    // Vec<String> 同样适用;迭代器先 map 再 collect 成 Vec 后 join
    let ports: Vec<String> = hosts.iter().map(|h| format!("{h}:443")).collect();
    println!("ports: {}", ports.join(" | "));

    // 数字切片 join 成逗号列表:报表最常见的一行代码
    let bytes = [512, 1_024, 4_096];
    println!("sizes: {}", bytes.iter().map(|b| b.to_string()).collect::<Vec<_>>().join(", "));

    // join 对 Option 有效:None 渲染为空段
    let maybe = [Some("a"), None, Some("b")];
    println!("maybe: {}", maybe.iter().map(|o| o.unwrap_or("")).collect::<Vec<_>>().join("/"));
}

How the snippet works

Join Iterator Elements With Separator keeps everything in the function main.

Applying it

The demo output is labeled (hosts:, ports:, sizes:), so every printed line maps back to its originating operation.

Statements that matter

let ports: Vec<String> = hosts.iter().map(|h| format!("{h}:443")).collect();
let maybe = [Some("a"), None, Some("b")];

Interactive Tools for This Topic

FAQ

What does Join Iterator Elements With Separator print when run?
Invoke the file as-is — the `hosts:`, `ports:`, `sizes:` prefixes identify which step printed each line.