官术网_书友最值得收藏!

  • Mastering Rust
  • Rahul Sharma Vesa Kaihlavirta
  • 325字
  • 2021-07-02 13:35:22

Linting code with clippy

Linting is a practice that helps maintain the quality of your library and have it adhere to standard coding idioms and practices. The de facto linting tool in the Rust ecosystem is clippy. Clippy provides us with a bunch of lints (about 291 at the time of writing this book) to ensure high quality Rust code. In this section, we'll install clippy and try it out on our libawesome library, add some dummy code to it, and see what suggestions we get from clippy. There are various ways of using clippy on your project, but we will use the cargo clippy subcommand way as that's simple. Clippy can perform analysis on code because it's a compiler plugin and has access to a lot of the compiler's internal APIs.

To use clippy, we need to install it by running rustup component add clippy. If you don't have it already, rustup will install it for you. Now, to demonstrate how clippy can point out bad style in our code, we have put some dummy statements within an if condition inside our pow function in the myexponent crate, as follows:

// myexponent/src/lib.rs

fn pow(base: i64, exponent: usize) -> i64 {
/////////////////// Dummy code for clippy demo
let x = true;
if x == true {

}
///////////////////
let mut res = 1;
...
}

With those lines added, by running cargo clippy in our myexponent directory, we get the following output:

Great! Clippy has found a common code style that is redundant, that is, checking for a Boolean value that is either true or false. Alternatively, we could have written the preceding if condition directly as if x {} . There are many more checks that clippy does, and some of them even point out potential mistakes in your code, such as https://rust-lang-nursery.github.io/rust-clippy/master/index.html#absurd_extreme_comparisons. To see all the available lints and various ways of configuring clippy, head over to https://github.com/rust-lang/rust-clippy.

主站蜘蛛池模板: 朔州市| 简阳市| 周至县| 清水河县| 芦山县| 饶河县| 同德县| 宁化县| 从江县| 三台县| 徐州市| 崇礼县| 大宁县| 洛浦县| 微山县| 无极县| 秦安县| 大关县| 台中市| 琼结县| 法库县| 和顺县| 清徐县| 青浦区| 乐山市| 安国市| 磐安县| 资阳市| 乌鲁木齐市| 和硕县| 项城市| 平度市| 虎林市| 太原市| 大竹县| 青浦区| 永州市| 宁津县| 凤凰县| 日土县| 修文县|