Skip to content
On this page

Clippy1: exercises/clippy/clippy1.rs

题目

rust
// 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
    )
}

Clippy工具是用于分析代码的lint集合,以便我们可以捕捉常见错误并改进Rust代码。

对于这些练习,当出现Clippy告警时,代码将无法编译,请检查输出中的Clippy建议,解决代码中的问题。

题目解析

错误信息如下:

txt
⚠️  Compiling of exercises/clippy/clippy1.rs failed! Please try again. Here's the output:
    Checking clippy1 v0.0.1 (/home/jeffery/dev/rust/rustlings/exercises/clippy)
error: approximate value of `f32::consts::PI` found
  --> clippy1.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 default

error: could not compile `clippy1` (bin "clippy1") due to previous error

错误信息提示我们3.14f32其实可以使用f32::const::PI来代替。

rust
use std::f32;

fn main() {
    let pi = 3.14f32; 
    let pi = f32::consts::PI; 
    let radius = 5.00f32;

    let area = pi * f32::powi(radius, 2);

    println!(
        "The area of a circle with radius {:.2} is {:.5}!",
        radius, area
    )
}

Powered by VitePress