Skip to content

to_string() in a format string when format specifiers are used (eg :<20) is NOT redundant #8855

@akanalytics

Description

@akanalytics

Summary

It is not true that
a) println!("{:<20}", struct.to_string());
gives the same result as
b) println!("{:<20}", struct)

It depend on how the formatter is written.
Line a) uses the default "{}" display to render a string then renders the string using the formatting rules :<20
Whereas b) uses the formatting rules of the struct's display, not the string's display trait impl.

Many dsiplay impls for objects do not have logic to cater for alignment for instance, but using struct.to_string() and then formatting with alignment format specifiiers DOES give alignment.

Clippy "fixing" such lines results in behavioural change.

I think clippy should flag only when the format is "{}"

Lint Name

to_string_in_format_args

Reproducer

I tried this code:

     write!(
                f,
                "{:>6} {:>10} {:>3} {:>2}",
                self.bm.uci(),
                self.score.to_string(),
                self.depth,
                self.nt
            )

I saw this happen:

6   | #![warn(clippy::perf)]
    |         ^^^^^^^^^^^^
    = note: `#[warn(clippy::to_string_in_format_args)]` implied by `#[warn(clippy::perf)]`
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#to_string_in_format_args

warning: `to_string` applied to a type that implements `Display` in `println!` args
   --> src/comms/bench.rs:118:19
    |
118 |                 cp.to_string(),
    |                   ^^^^^^^^^^^^ help: remove this

This is related to #7729

Version

rustc 1.60.0 (7737e0b5c 2022-04-04)
binary: rustc
commit-hash: 7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c
commit-date: 2022-04-04
host: x86_64-unknown-linux-gnu
release: 1.60.0
LLVM version: 14.0.0

Additional Labels

No response

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 have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions