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

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.

主站蜘蛛池模板: 广河县| 汝阳县| 兰坪| 勐海县| 房产| 剑川县| 石门县| 宿松县| 仪征市| 盐城市| 阿拉尔市| 且末县| 米泉市| 凤阳县| 四子王旗| 福贡县| 孝昌县| 沂南县| 黔东| 乐陵市| 三都| 远安县| 岚皋县| 缙云县| 景宁| 克东县| 洪江市| 大化| 乌恰县| 柳林县| 巴里| 惠州市| 叶城县| 疏附县| 靖边县| 吐鲁番市| 毕节市| 刚察县| 仲巴县| 沙坪坝区| 蕉岭县|