Rust Formatting (format!) 🎯

beginner
25 min

Rust Formatting (format!) 🎯

Welcome to the Rust Formatting tutorial! In this lesson, we'll dive deep into formatting in Rust and learn how to make our code clean, readable, and easy to maintain.

What is Formatting in Rust? 📝

Formatting in Rust refers to the arrangement of code, including indentation, line breaks, and whitespace, to make it more readable and easier to understand. Rust enforces a strict set of rules for formatting, known as the Rust Formatter (rustfmt).

Why is Formatting Important? 💡

Good formatting makes code more readable, which in turn makes it easier to understand, debug, and maintain. It reduces the cognitive load for readers and helps them follow the flow of the code more easily.

Installing Rust Formatter (rustfmt) 📝

Before we start formatting our code, we need to make sure that we have the Rust Formatter (rustfmt) installed. You can install it using the following command:

bash
rustup component add rustfmt

Basic Formatting Rules 📝

Rust has several formatting rules that we should follow to ensure our code is consistent and easy to read. Here are some of the most important ones:

  1. Indentation: Rust uses 4 spaces for indentation.
  2. Line Breaks: Break lines at logical points and use a single line for simple statements.
  3. Whitespace: Use whitespace to separate elements and make the code more readable.

Formatting a Simple Function 🎯

Let's format a simple function using rustfmt.

Before Formatting:

rust
fn main() { let x = 5; let y = 10; let sum = x + y; println!("The sum is {}", sum); }

After Formatting:

rust
fn main() { let x = 5; let y = 10; let sum = x + y; println!("The sum is {}", sum); }

Formatting Multiline Statements 🎯

Rust allows us to write multiline statements by using the \ character. However, it's best to avoid them when possible.

Before Formatting:

rust
fn main() { let long_string = "This is a very long string that goes on for several lines."; println!("{}", long_string); }

After Formatting:

rust
fn main() { let long_string = "This is a very long string that goes on for several lines."; println!("{}", long_string); }

Formatting Blocks 🎯

In Rust, blocks of code are enclosed in curly braces {}. It's important to indent them properly.

Before Formatting:

rust
fn main() { if 5 > 3 { println!("5 is greater than 3!"); } else { println!("5 is not greater than 3!"); } }

After Formatting:

rust
fn main() { if 5 > 3 { println!("5 is greater than 3!"); } else { println!("5 is not greater than 3!"); } }

Formatting Modules 🎯

In Rust, we organize our code into modules. Here's how to format a module:

rust
// main.rs mod utils; fn main() { utils::hello(); } // utils.rs pub fn hello() { println!("Hello, world!"); }

Quiz: Formatting a Function 🎯

Quick Quiz
Question 1 of 1

Given the following function, format it using `rustfmt`.