Rustfmt: The Ultimate Guide to Formatting Your Rust Code

Porthos Fu
2 min readFeb 2, 2023

--

This article was originally published on our website https://isab.run. The Medium version offers the same in-depth content and insights.

Rustfmt is a tool for formatting Rust code according to a set of customizable rules. It is designed to be used as a command-line tool and can be integrated into various development environments. The tool is based on the official Rust style guide, and it can automatically format code to conform to the guide’s recommendations.

To use rustfmt, you need to first install it by adding the following line to your Cargo.toml file:

[dependencies]
rustfmt = "version"

Once rustfmt is installed, you can use the cargo fmt command to format your code. This command will automatically detect and format all the .rs files in your project. You can also specify specific files or directories to be formatted by passing them as arguments to the command.

In addition to the default formatting rules, rustfmt also allows you to customize the formatting of your code using a .toml configuration file. This file can be placed in the root of your project, or in your home directory, and it allows you to specify specific rules for formatting your code.

For example, you can use the max_width setting to specify the maximum line width for your code. You can also use the struct_literal_style setting to specify whether struct literals should be formatted with or without spaces between the fields and values.

You can also use the --check flag to check your code for formatting issues without modifying it. This is useful for running rustfmt as part of a continuous integration pipeline.

In addition to the command-line interface, rustfmt also provides an API that allows you to integrate it into other tools and IDEs. This allows you to format your code automatically as you type, or to use rustfmt as part of a larger automated code analysis and formatting pipeline.

Overall, rustfmt is a powerful tool for formatting Rust code and ensuring consistency across your codebase. By providing an easy-to-use command-line interface, a customizable configuration file, and an API, rustfmt makes it easy to integrate formatting into your development workflow.

References:

--

--

Porthos Fu

Porthos Fu, ISAB Executive Committee member. Focuses on organizing activities and recruiting new members. Visit https://isab.run/ for ISAB News & Updates