How it works...

In this recipe, we basically introduce the rustfmt tool that helps us follow the correct style guide implied by the Rust programming language in an automated manner, where the developer can freely use the tool to follow style standards.

From the output of the main.rs file, we can see that the wrong indentation in the code was automatically corrected and overwritten in the main.rs file with the cargo fmt command, and that a backup of the previous code was saved in the main.rs.bk file.

There are various modes in which we can run the rustfmt tool, as follows:

  • replace: This is the default selection that overwrites the original files and creates backup files after formatting; cargo fmt uses --write-mode=replace by default.
  • overwrite: This option basically changes the original files without creating a backup of the previous code.
  • display: This option basically prints the formatted files to stdout, that shows the changes made in the terminal screen.
  • diff: This option prints the difference between the original files and formatted files to stdout. This will also exit with an error code if there are any differences.
  • checkstyle: This option will output the lines that need to be corrected as a checkstyle XML file that can be used with tools such as Jenkins.

In order to use these write modes, we need to install the rustfmt tool by source, where we clone the main GitHub repository and install from the source with the following code:

cargo install --path 

This enables us to run formatting commands on any Rust files with various modes, such as the following example:

rustfmt main.rs

rustfmt --write-mode=overwrite main.rs
It is a good practice to run the rustfmt tool before building the project so that we can maintain code standards without much effort. The ideal way to do this is to configure the rustfmt tool in your favorite text editor and have the rustfmt commands as a part of the build process.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.76.164