Code formatting and linting

Format your code

rustfmt-nightly rustfmt-nightly-crates.io rustfmt-nightly-github rustfmt-nightly-lib.rs cat-development-tools cat-development-tools::cargo-plugins

# 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

clippy clippy-crates.io clippy-github clippy-lib.rs cat-development-tools cat-development-tools::cargo-plugins

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

rustfix rustfix-crates.io rustfix-github rustfix-lib.rs cat-development-tools cat-development-tools::cargo-plugins

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 cargo-husky-crates.io cargo-husky-github cargo-husky-lib.rs cat-development-tools

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.