Format Rust source with rustfmt

Enforce consistent Rust code layout on Red Hat Enterprise Linux by using rustfmt, the formatting tool in Rust Toolset. Use rustfmt as a standalone tool or with Cargo to apply standard Rust formatting rules across your projects.

Install rustfmt

Install the rustfmt formatting tool by installing the rustfmt package (RHEL 8 module or RHEL 9 and 10 package).

Before you begin

Procedure

Install the rustfmt package:
  • On RHEL 8, enter:
    # yum install rustfmt
  • On RHEL 9 and 10, enter:
    # dnf install rustfmt

Use rustfmt as a standalone tool

Use rustfmt as a standalone tool to format a Rust source file and its dependencies, or use it with the Cargo build tool.

Before you begin

Procedure

Format the Rust source code:
$ rustfmt <source_file>

Replace <source_file> with the name of your source file. If you use standard input instead, formatted output is printed to standard output.

Important

By default, rustfmt modifies the affected files without displaying details or creating backups. To display details and create backups, run rustfmt with the --write-mode option.

Use rustfmt with the Cargo build tool

Use the rustfmt tool with Cargo to format a Rust source file and all its dependencies. As an alternative, use rustfmt as a standalone tool. For more information, see Use rustfmt as a standalone tool.

Before you begin

Procedure

  1. Optional: To change the rustfmt formatting options, create rustfmt.toml configuration file in the project directory and add your configurations to the file.
  2. Format the Rust source code:
    $ cargo fmt