rspec/rules/S6164/rust/rule.adoc
github-actions[bot] feaf726b3a
Create rule S6164: Mathematical constants should not be hardcoded (#4690)
* Add rust to rule S6164

* Add rule description

* Update rule.adoc

* Add link to Clippy lint

---------

Co-authored-by: sallaigy <sallaigy@users.noreply.github.com>
Co-authored-by: Gyula Sallai <gyula.sallai@sonarsource.com>
Co-authored-by: yassin-kammoun-sonarsource <yassin.kammoun@sonarsource.com>
2025-03-19 14:08:57 +00:00

41 lines
1.2 KiB
Plaintext

== Why is this an issue?
Floating-point literals that approximate constants defined in `std::f32::consts` or `std::f64::consts` should be replaced with the predefined constants. Using the standard library constants ensures higher precision and avoids potential rounding errors that can occur when manually approximating these values. It also improves code readability and maintainability, as it clearly indicates the intended constant value.
=== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
let x = 3.14; // Noncompliant: Approximates PI
let y = 1_f64 / 3.1415926535; // Noncompliant: Approximates FRAC_1_PI
----
=== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
use std::f32::consts::PI;
use std::f64::consts::FRAC_1_PI;
let x = PI; // Compliant: Uses the predefined PI constant
let y = FRAC_1_PI; // Compliant: Uses the predefined FRAC_1_PI constant
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
=== is related to: S2904
=== is related to: S109
endif::env-github,rspecator-view[]