Skip to content

Warn on push_str(&format!()) #6261

@kangalio

Description

@kangalio

What it does

Emits a warning on code like ```rust
some_string.push_str(&format!(...));
// or
some_string += &format!(...);

and suggests rewriting it to ```rust
write!(&mut some_string, ...);

Categories

  • Kind: Perf

What is the advantage of the recommended code over the original code
It avoids one extra heap allocation by writing directly to the existing String instead of creating a new temporary String.

Drawbacks

The user has to use std::io::Write for the write! macro to work (which I don't get tbh, why can't write! just import the trait on its own...)

Example

let mut string = String::new();
for foo in foo_list {
    string += &format!("{:?}", foo);
}

Could be written as:

use std::io::Write;

let mut string = String::new();
for foo in foo_list {
    write!(&mut string, "{:?}", foo);
}

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsL-perfLint: Belongs in the perf lint groupT-middleType: Probably requires verifiying typesgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions