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.
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).
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.
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:
rustup component add rustfmtRust 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:
Let's format a simple function using rustfmt.
Before Formatting:
fn main() {
let x = 5;
let y = 10;
let sum = x + y;
println!("The sum is {}", sum);
}After Formatting:
fn main() {
let x = 5;
let y = 10;
let sum = x + y;
println!("The sum is {}", sum);
}Rust allows us to write multiline statements by using the \ character. However, it's best to avoid them when possible.
Before Formatting:
fn main() {
let long_string = "This is a very long string
that goes on for several lines.";
println!("{}", long_string);
}After Formatting:
fn main() {
let long_string = "This is a very long string
that goes on for several lines.";
println!("{}", long_string);
}In Rust, blocks of code are enclosed in curly braces {}. It's important to indent them properly.
Before Formatting:
fn main() {
if 5 > 3 {
println!("5 is greater than 3!");
} else {
println!("5 is not greater than 3!");
}
}After Formatting:
fn main() {
if 5 > 3 {
println!("5 is greater than 3!");
} else {
println!("5 is not greater than 3!");
}
}In Rust, we organize our code into modules. Here's how to format a module:
// main.rs
mod utils;
fn main() {
utils::hello();
}
// utils.rs
pub fn hello() {
println!("Hello, world!");
}Given the following function, format it using `rustfmt`.