Skip to content

format_in_format_args lint suggests code that results in alternative behaviour #8643

Closed
@rossmacarthur

Description

@rossmacarthur

Summary

I have some code that looks like this

fn tabulate(devices: Vec<Device>) -> String {
    let mut s = String::from("Vendor ID  Product ID  Name\n");
    s.push_str("---------  ----------  ----------------------------------\n");
    for d in devices {
        s.push_str(&format!(
            "{:<9}  {:<10}  {}",
            format!("0x{:x}", d.vendor_id),
            format!("0x{:x}", d.product_id),
            d.name,
        ));
    }
    s
}

Clippy complains about the inner format! but replacing them with format_args! doesn't align to the columns properly.

Lint Name

format_in_format_args

Reproducer

I tried this code:

fn main() {
    println!(
        "{:>9} {:>10}",
        format!("0x{:x}", 42),
        format!("0x{:x}", 1337)
    );
}

I saw this happen:

warning: `format!` in `println!` args
 --> src/main.rs:2:5
  |
2 | /     println!(
3 | |         "{:>9} {:>10}",
4 | |         format!("0x{:x}", 42),
5 | |         format!("0x{:x}", 1337)
6 | |     );
  | |_____^
  |
  = note: `#[warn(clippy::format_in_format_args)]` on by default
  = help: combine the `format!(..)` arguments with the outer `println!(..)` call
  = help: or consider changing `format!` to `format_args!`
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#format_in_format_args

I expected to see this happen:

No lint emitted, or a better suggestion

Version

rustc 1.62.0-nightly (306ba8357 2022-04-05)
binary: rustc
commit-hash: 306ba8357fb36212b7d30efb9eb9e41659ac1445
commit-date: 2022-04-05
host: aarch64-apple-darwin
release: 1.62.0-nightly
LLVM version: 14.0.0

Additional Labels

@rustbot label +I-suggestion-causes-error

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions