Code Formatting and Linting
Recipe | Crates | Categories |
---|---|---|
Format Your Code | ||
Lint Your Code | ||
Fix Compiler Warnings Automatically | ||
Format or Lint Your Code Before Committing it |
Topic | Rust Crates |
---|---|
Linting | cargo clippy is the primary linter for Rust code, catching stylistic issues and potential bugs. rust-analyzer : While primarily an LSP (Language Server Protocol) implementation for IDEs, it also performs code analysis checks. |
Formatting | cargo fmt is the standard Rust code formatter. |
Dead Link Detection | cargo deadlinks finds broken links in your documentation. |
Format Your Code
# Install `rustfmt` if needed
rustup component add rustfmt
cargo fmt
# Fails if code is not formatted; use in CD / CI
cargo fmt -- --check
Lint Your Code
cargo-clippy
⮳ is the official Rust linter. It catches common mistakes and improves your Rust code.
rustup component add clippy # install if needed
cargo clippy
Mute a warning using the #[allow(clippy::lint_name)]
attributes.
Fix Compiler Warnings Automatically
Can automatically fix compiler warnings that have a clear way to correct the problem that's likely what you want.
cargo fix
Format or Lint Your Code Before Committing it
cargo-husky⮳ setup Git hooks automatically for cargo
⮳ projects with 🐶
Git hook scripts are useful for identifying simple issues (failing tests, trailing white spaces, formatting of the code, of JSON, and YAML files...) before committing code, prior to submission to code review.
Add the cargo-husky
⮳ crate to the [dev-dependencies]
section of your project's Cargo.toml
⮳.
[dev-dependencies]
cargo-husky = "1"
Then run tests in your project directory.
cargo test
See also pre-commit
⮳, which is a Python framework for managing and maintaining multi-language pre-commit hooks.