Chapter 3. rustfmt

The rustfmt tool provides automatic formatting of Rust source code.

3.1. Installing rustfmt

Run the following command to install rustfmt:

  • For Red Hat Enterprise Linux 7:

    # yum install rust-toolset-1.45-rustfmt
  • For Red Hat Enterprise Linux 8:

    # yum install rustfmt

3.2. Using rustfmt as a standalone tool

To format a Rust source file and all its dependencies with the rustfmt tool:

  • For Red Hat Enterprise Linux 7:

    $ scl enable rust-toolset-1.45 'rustfmt source-file'
  • For Red Hat Enterprise Linux 8:

    $ rustfmt source-file

Replace source-file with the path to a source file.

By default, rustfmt modifies the affected files in place without displaying details or creating backups. To change the behavior, use the --write-mode value option. For further details see the help message of rustfmt:

  • For Red Hat Enterprise Linux 7:

    $ scl enable rust-toolset-1.45 'rustfmt --help'
  • For Red Hat Enterprise Linux 8:

    $ rustfmt --help

Additionally, rustfmt accepts standard input instead of a file and provides its output in standard output.

Note

You can execute any command using the scl utility on Red Hat Enterprise Linux 7, causing it to be run with the Rust binaries available. To use Rust Toolset on Red Hat Enterprise Linux 7 without a need to use scl enable with every command, run a shell session with:

$ scl enable rust-toolset-1.45 'bash'

3.3. Using rustfmt with Cargo

To format all source files in a cargo crate:

  • For Red Hat Enterprise Linux 7:

    $ scl enable rust-toolset-1.45 'cargo fmt'
  • For Red Hat Enterprise Linux 8:

    $ cargo fmt

To change the rustfmt formatting options, create the configuration file rustfmt.toml in the project directory and supply the configuration there. For further details see the help message of rustfmt:

  • For Red Hat Enterprise Linux 7:

    $ scl enable rust-toolset-1.45 'rustfmt --help'
  • For Red Hat Enterprise Linux 8:

    $ rustfmt --help
Note

You can execute any command using the scl utility on Red Hat Enterprise Linux 7, causing it to be run with the Rust binaries available. To use Rust Toolset on Red Hat Enterprise Linux 7 without a need to use scl enable with every command, run a shell session with:

$ scl enable rust-toolset-1.45 'bash'

3.4. Additional resources

  • Help message of rustfmt:

    • For Red Hat Enterprise Linux 7:

      $ scl enable rust-toolset-1.45 'rustfmt --help'
    • For Red Hat Enterprise Linux 8:

      $ rustfmt --help
  • Configuring Rustfmt in Configurations.md:

    • Location in Red Hat Enterprise Linux 7:

      /opt/rh/rust-toolset-1.45/root/usr/share/doc/rust-toolset-1.45-rustfmt-1.45.1/Configurations.md

    • Location in Red Hat Enterprise Linux 8:

      /usr/share/doc/rustfmt/Configurations.md