# clippy and rustfmt — Rust

Source: https://www.skillbyai.com/en/rust/q-clippy

> Idioms and formatting, automated.

## Hundreds of lints, one format

`cargo clippy` runs hundreds of lints that catch non-idiomatic, inefficient or suspicious code and usually suggest the fix. `cargo fmt` formats code in the standard style; `cargo fmt -- --check` fails CI when files are not formatted. Run both in CI with warnings treated as errors (`cargo clippy -- -D warnings`) to keep a codebase consistent.

## clippy suggestions on beginner code, run

I ran this with Rust 1.99.0 (cargo run, edition 2024, standard library only). clippy flags comparing len() to zero (use is_empty), total = total + x (use +=), a loop variable used only for indexing (iterate directly), and an unnecessary vec! (a plain array works). Output shows the warning titles.

```rust
fn main() {
    let items = vec![1, 2, 3];
    let mut total = 0;
    for i in 0..items.len() {
        total = total + items[i];
    }
    if total == 6 { println!("total is six") } else { println!("other") }
    let name = String::from("pen");
    let len = name.len() == 0;
    println!("{len}");
}
```

Output:

```
warning: length comparison to zero
warning: manual implementation of an assign operation
warning: the loop variable `i` is only used to index `items`
warning: useless use of `vec!`
```

## rustfmt on a one-line program, run

I ran this with Rust 1.99.0 (cargo run, edition 2024, standard library only). cargo fmt --check shows the diff it would apply: the cramped line becomes properly indented, spaced code.

```rust
fn main(){let x=vec![1,2,3];for v in x.iter(){println!("{}",v);}}
```

Output:

```
-fn main(){let x=vec![1,2,3];for v in x.iter(){println!("{}",v);}}
+fn main() {
+    let x = vec![1, 2, 3];
+    for v in x.iter() {
+        println!("{}", v);
+    }
+}
```

**Quiz:** What does cargo clippy do?

- [ ] Downloads crates
- [ ] Formats code
- [x] Lints code for common mistakes and non-idiomatic patterns
- [ ] Profiles performance

*Answer:* Lints code for common mistakes and non-idiomatic patterns. rustfmt formats; clippy lints.
