Rustfmt is a code formatting tool for the Rust programming language. It helps developers maintain a consistent coding style across their projects, making the codebase more readable and maintainable. This article will guide you through the process of installing Rustfmt, configuring it, and using it to format your Rust code.
Rustfmt is part of the Rust toolchain, so if you have Rust installed, you likely already have Rustfmt. To check if Rustfmt is installed, run the following command:
rustup component list | grep rustfmt
If you see rustfmt
as an installed component, you’re good to go. If not, install it by running:
rustup component add rustfmt
Rustfmt offers several configuration options to customize the formatting style. To configure Rustfmt, create a rustfmt.toml
or .rustfmt.toml
file in the root of your project.
Here’s a sample configuration file with some commonly used options:
edition = "2021"
max_width = 100
hard_tabs = false
tab_spaces = 4
newline_style = "Auto"
use_small_heuristics = "Default"
edition
: Specifies the Rust edition to use, e.g., “2015”, “2018”, or “2021”.max_width
: The maximum line width for your code. Default is 100 characters.hard_tabs
: Use hard tabs instead of spaces for indentation. Default is false
.tab_spaces
: The number of spaces per indentation level. Default is 4 spaces.newline_style
: The line ending style to use. Options are “Auto”, “Native”, “Unix”, and “Windows”.use_small_heuristics
: Determines the heuristic used for fitting items within the max_width
. Options are “Default”, “Max”, “Off”, and “Minimum”.For a complete list of configuration options, refer to the official Rustfmt configuration documentation.
To format a single Rust file, run the following command:
rustfmt path/to/your_file.rs
To format all Rust files in your project, run the following command from your project’s root directory:
cargo fmt
You can also check if your code is formatted correctly without actually modifying the files by running:
cargo fmt -- --check
This command will return a non-zero exit code if any file requires formatting.
Most modern IDEs and text editors support Rustfmt integration. Here are a few examples:
:RustFmt
command to format the current file.Using Rustfmt allows you to maintain a consistent coding style in your Rust projects, improving code readability and maintainability. By configuring Rustfmt to your preferred style and integrating it into your development environment, you can ensure that your code is always formatted properly.