- 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.
- Mastering AWS Lambda
- Learning Cython Programming(Second Edition)
- Visual Basic程序設(shè)計教程
- 微信公眾平臺開發(fā):從零基礎(chǔ)到ThinkPHP5高性能框架實踐
- Getting Started with Laravel 4
- PHP+Ajax+jQuery網(wǎng)站開發(fā)項目式教程
- TMS320LF240x芯片原理、設(shè)計及應(yīng)用
- 細(xì)說Python編程:從入門到科學(xué)計算
- 時空數(shù)據(jù)建模及其應(yīng)用
- 并行編程方法與優(yōu)化實踐
- 虛擬現(xiàn)實建模與編程(SketchUp+OSG開發(fā)技術(shù))
- 關(guān)系數(shù)據(jù)庫與SQL Server 2012(第3版)
- Building Apple Watch Projects
- C++面向?qū)ο蟪绦蛟O(shè)計
- R語言數(shù)據(jù)分析從入門到實戰(zhàn)