How to use the command 'cargo fmt' (with examples)
This article will guide you through the various use cases of the cargo fmt
command in Rust, which is used to run rustfmt
on all source files in a Rust project. rustfmt
is a tool that automatically formats Rust code according to a set of style guidelines.
Use case 1: Format all source files
Code:
cargo fmt
Motivation:
Formatting code is important for readability and maintainability. In a Rust project, running cargo fmt
will automatically format all the source files in the project directory, ensuring consistent code styling throughout the project.
Explanation:
The command cargo fmt
is used to run rustfmt
on all the source files in the Rust project. It locates and formats any files with the “.rs” extension.
Example output:
Formatting src/main.rs
Formatting src/lib.rs
Finished formatting
Use case 2: Check for formatting errors without writing to the files
Code:
cargo fmt --check
Motivation:
Before committing or publishing code, it’s important to ensure that there are no formatting errors. Running cargo fmt --check
allows you to check for any formatting issues without modifying the files, helping to maintain consistent code style.
Explanation:
The --check
argument, when passed to cargo fmt
, performs a dry run by checking for formatting errors without actually modifying any files in the project. It identifies any inconsistencies in code styling or formatting issues.
Example output:
src/main.rs is already correctly formatted.
src/lib.rs is already correctly formatted.
Use case 3: Pass arguments to each rustfmt
call
Code:
cargo fmt -- rustfmt_args
Motivation:
The --
symbol is used to pass arguments to rustfmt
from within the cargo fmt
command. This enables you to customize the behavior of rustfmt
according to your specific requirements.
Explanation:
The rustfmt_args
argument can be replaced with any arguments that are accepted by rustfmt
itself. These arguments will be passed directly to each rustfmt
call made by cargo fmt
, allowing you to configure the code formatting process.
Example output:
Formatting src/main.rs with additional arguments: --tabs
Formatting src/lib.rs with additional arguments: --edition 2018
Finished formatting
Conclusion:
The cargo fmt
command is a powerful tool for automatically formatting Rust code in a project. By using various arguments, such as --check
and rustfmt_args
, you can adapt the formatting process to your specific needs. Regularly running cargo fmt
helps maintain a consistent code style and improves the readability of your codebase.