Rust-- 编程好帮手 cargo clippy, cargo fmt

1,185 阅读1分钟

cargo run, cargo build, cargo check 可以检查代码是否有编译错误

cargo fmt 可以帮助将代码的格式美化

cargo clippy,可以给出类似于cargo run/build/check时候的编译warnings 还可以给出提示和指引,帮助改进代码,下面举例说明:

fn main() {
    let MY_LIST = ["one", "two", "three"];
    for i in 0..MY_LIST.len() {
        println!("got {}", MY_LIST[i]);
    }
}

在终端中执行 cargo clippy后提示:

warning: the loop variable `i` is only used to index `MY_LIST`
 --> src/main.rs:3:14
  |
3 |     for i in 0..MY_LIST.len() {
  |              ^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(clippy::needless_range_loop)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_range_loop
help: consider using an iterator
  |
3 |     for <item> in &MY_LIST {
  |         ~~~~~~    ~~~~~~~~




warning: variable `MY_LIST` should have a snake case name
 --> src/main.rs:2:9
  |
2 |     let MY_LIST = ["one", "two", "three"];
  |         ^^^^^^^ help: convert the identifier to snake case: `my_list`
  |
  = note: `#[warn(non_snake_case)]` on by default
  
  
可以看到, clippy 给出了两点建议:
1. the loop variable `i` is only used to index `MY_LIST`,它建议使用iterator来遍历
2. MY_LIST命名没有采用推荐的snake命名法,它建议改为 my_list

按照clippy的建议修改之后,代码如下:

// 再次执行 cargo clippy, 不再有新的建议提示
fn main() {
    let my_list = ["one", "two", "three"];
    for item in &my_list {
        println!("got {}", item);
    }
}


如果你感觉clippy的提示不够啰嗦,还能忍受,可以配置让其严格程度更高, 使用方法,在main.rs文件的首行加入 #[warn(clippy::all, clippy::pedantic)]

// 刚开始学习rust会不习惯,随着熟练度增加, clippy或者rust compiler会变成你编程路上的好朋友,帮助你写出更严格更准确的代码

#[warn(clippy::all, clippy::pedantic)]