Inherent method uses a name that belongs to a standard trait
ID |
rust.maintainability.should_implement_trait |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Api Design |
Language |
Rust |
Description
Reports an inherent impl block that defines a method whose name is the method of a standard library trait - add, next, default, from_str, clone, cmp, deref and the like - instead of implementing that trait.
Rationale
The name creates an expectation the type does not meet: callers cannot use +, a for loop, ?, .collect() or any generic function bounded on the trait, because the type does not implement it. Worse, the inherent method takes precedence over the trait method during resolution, so if the trait is implemented later the two silently coexist and which one runs depends on how the call is written.
The following code illustrates the pattern detected by this rule:
use std::fmt;
pub struct Money {
cents: i64,
}
// FLAGGED: Inherent method uses a name that belongs to a standard trait
impl Money {
pub fn add(&self, other: &Money) -> Money {
Money { cents: self.cents + other.cents }
}
pub fn cents(&self) -> i64 {
self.cents
}
}