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
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
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")
}
}