rspec/rules/S7440/rust/rule.adoc
github-actions[bot] 6919fdfd79
Create rule S7440: Formatting trait implementations should not be recursive (#4783)
* Create rule S7440

* Update RSPEC

---------

Co-authored-by: yassin-kammoun-sonarsource <yassin-kammoun-sonarsource@users.noreply.github.com>
Co-authored-by: yassin-kammoun-sonarsource <yassin.kammoun@sonarsource.com>
2025-03-19 13:06:39 +00:00

39 lines
850 B
Plaintext

== Why is this an issue?
Recursive calls in formatting trait implementations (e.g., `Display`) will lead to infinite recursion and a stack overflow.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
use std::fmt;
struct Structure(i32);
impl fmt::Display for Structure {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_string()) // Noncompliant
}
}
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
use std::fmt;
struct Structure(i32);
impl fmt::Display for Structure {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0) // Compliant
}
}
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#recursive_format_impl