Finding Common Mistakes with Clippy

Hands-on Rust — by Herbert Wolverson (19 / 120)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Formatting Your Code | TOC | Package Management with Cargo 👉

Rust ships with a tool called Clippy. Clippy provides hints and guidance while you code. You can type cargo clippy at any time to get a list of suggestions for your project. Many clippy warnings will also appear when you compile your programs. Most development environments that support Rust integrate with Clippy and will show you warnings and hints as you work.

Let’s use Clippy to fix a simple project. Create a new project by navigating to your source code folder and typing cargo new clippy (see Starting a New Project with Cargo). Edit your src/main.rs file to contain the following:

InstallingRust/Clippy/src/main.rs

​ ​fn​ ​main​() {
​ ​let​ MYLIST = [ ​"One"​, ​"Two"​, ​"Three"​ ];
​ ​for​ i in 0..3 {
​ println!(​"{}"​, MYLIST[i]);
​ }
​ }

Run the program by typing cargo run into your terminal. You will see the following (as well as several warnings about the code):

​=> ​cargo run​
​<= One
​ Two
​ Three

The program works but has room for improvement. It’s ignoring some of Rust’s better features and naming conventions. These are common issues and Clippy can help. Type cargo clippy into your terminal, and you’ll receive a list of suggestions. The first warning is:

​ Checking clippy…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.