rspec/rules/S6164/rust/rule.adoc

41 lines
1.2 KiB
Plaintext
Raw Normal View History

== 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[]