47 lines
1.1 KiB
Plaintext
47 lines
1.1 KiB
Plaintext
|
|
== Why is this an issue?
|
|
Defining an inherent `to_string(&self)` method on a type that also implements the `Display` trait can lead to confusion, as this inherent method will overshadow the `to_string` method automatically provided by the `Display` trait. The inherent method is less versatile, preventing proper use of the `Display` trait's feature.
|
|
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
[source,rust,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
use std::fmt;
|
|
|
|
pub struct A;
|
|
|
|
impl A {
|
|
pub fn to_string(&self) -> String {
|
|
"I am A".to_string() // Noncompliant: Inherent method shadows `Display::to_string`.
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for A {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
write!(f, "I am A, too")
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,rust,diff-id=1,diff-type=compliant]
|
|
----
|
|
use std::fmt;
|
|
|
|
pub struct A;
|
|
|
|
impl fmt::Display for A {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
write!(f, "I am A")
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#inherent_to_string_shadow_display
|