Formatting Your Code
Hands-on Rust — by Herbert Wolverson (18 / 120)
👈 Using Cargo to Build, Check, or Run Your Proje ct | TOC | Finding Common Mistakes with Clippy 👉
When you’re sharing your code with others, it’s helpful to have a standardized layout for your code. Rust provides a style guide, but it can be difficult to remember.[13] Rust includes a formatter that can help you adhere to the standard. The command cargo fmt will reformat your code to follow the Rust style guide.
Suppose you were in a hurry and wrote “Hello, World!” as a one-line program:
fn main() { println!("Hello, world!"); }
This program will compile and run, but it’s very different from the recommended style guide. If you were to share it with your coworkers or as part of an open-source project, you would likely receive comments on the formatting. You can run cargo fmt to transform the terse code back into the recommended format.
When you run cargo fmt, it formats your entire project. I recommend running it regularly while you work, keeping your project’s formatting consistent. If you dislike its formatting, it has a lot of options for configuring it.[14]
The formatted result looks much better:
fn main() {
println!("Hello, world!");
}
Rust also includes tools to help you find issues with the content of your code.
👈 Using Cargo to Build, Check, or Run Your Proje ct | TOC | Finding Common Mistakes with Clippy 👉
Hands-on Rust by Herbert Wolverson can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.