Formatting Your Code

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 ...

Get Hands-on Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.