Rustlings: clippy1.rs #Issue84— Clippy in Rust
Rustlings Challenge: clippy1.rs Solution Walkthrough

This is the Eighty-fourth (84th) issue of the Rustlings series. In this issue, we provide solutions to Rustlings exercises along with detailed explanations. In this issue we will solve the challenge on clippy1.rs.
Previous challenge #Issue 83
Clippy is a popular and widely used tool in the Rust ecosystem. It is a collection of linters that are designed to analyze your Rust code for potential issues, bugs, and style violations.
Clippy provides warnings and suggestions to help us write safer, more idiomatic, and high-quality Rust code.
Challenge:
// clippy1.rs
//
// The Clippy tool is a collection of lints to analyze your code so you can
// catch common mistakes and improve your Rust code.
//
// For these exercises the code will fail to compile when there are clippy
// warnings check clippy's suggestions from the output to solve the exercise.
//
// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
use std::f32;
fn main() {
let pi = 3.14f32;
let radius = 5.00f32;
let area = pi * f32::powi(radius, 2);
println!(
"The area of a circle with radius {:.2} is {:.5}!",
radius, area
)
}Explanation:
Clippy throws an error that wants us to use the constant pi.
error: approximate value of `f32::consts::PI` found
--> src/lib.rs:17:14
|
17 | let pi = 3.14f32;
| ^^^^^^^
|
= help: consider using the constant directly
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant
= note: `#[deny(clippy::approx_constant)]` on by defaultClippy linter provides suggestions for improving the code quality and recommends not using approximate constants like 3.14 directly.
To fix this clippy warning, we can use the constant provided by the standard library for π (pi) directly.
Solution:
use std::f32::consts::PI;
fn main() {
let radius = 5.00f32;
let area = PI * f32::powi(radius, 2);
println!(
"The area of a circle with radius {:.2} is {:.5}!",
radius, area
);
}Resources
Before you go
Thank you for taking the time to read through this challenge. We invite you to share your knowledge of Rust as well. If you found this article valuable, please don’t hesitate to share it with others. Don’t forget to follow the publication and give the article some claps 👏.
Thank you, and we look forward to seeing you for the next challenges!
