Skip to content

to_string_trait_impl does not account for specialized implementations #12263

Closed
@DaniPopes

Description

@DaniPopes

Summary

With #![feature(min_specialization)] it is possible to implement both std::fmt::Display and ToString, however clippy emits a warning on the ToString implementation saying that Display should be implemented instead.

Lint Name

to_string_trait_impl

Reproducer

I tried this code (playground):

#![feature(min_specialization)]

pub struct MyStringWrapper<'a>(&'a str);

impl std::fmt::Display for MyStringWrapper<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

// Specialize `ToString` implementation to not go through `std::fmt`.
impl ToString for MyStringWrapper<'_> {
    fn to_string(&self) -> String {
        self.0.to_string()
    }
}

I saw this happen:

warning: direct implementation of `ToString`
  --> src/lib.rs:12:1
   |
12 | / impl ToString for MyStringWrapper<'_> {
13 | |     fn to_string(&self) -> String {
14 | |         self.0.to_string()
15 | |     }
16 | | }
   | |_^
   |
   = help: prefer implementing `Display` instead
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#to_string_trait_impl
   = note: `#[warn(clippy::to_string_trait_impl)]` on by default

I expected to see this happen: no warnings emitted

Version

rustc 1.78.0-nightly (d44e3b95c 2024-02-09)
binary: rustc
commit-hash: d44e3b95cb9d410d89cb8ab3233906a33f43756a
commit-date: 2024-02-09
host: x86_64-unknown-linux-gnu
release: 1.78.0-nightly
LLVM version: 17.0.6

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