RS.CLIPPY.FORMAT_COLLECT

`format!`ing every element in a collection, then collecting the strings into a new `String`

This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: format_collect. Copyright ©2025 The Rust Team. All rights reserved.

What it does

Checks for usage of .map(|_| format!(..)).collect::<String>().

Why is this bad?

This allocates a new string for every element in the iterator. This can be done more efficiently by creating the String once and appending to it in Iterator::fold, using either the write! macro which supports exactly the same syntax as the format! macro, or concatenating with + in case the iterator yields &str/String.

Note also that write!-ing into a String can never fail, despite the return type of write! being std::fmt::Result, so it can be safely ignored or unwrapped.

Example

fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02X}")).collect()
}

Use instead:

use std::fmt::Write;
fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().fold(String::new(), |mut output, b| {
        let _ = write!(output, "{b:02X}");
        output
    })
}