Search⌘ K

Blocks and Statements

Explore how Rust's blocks function as expressions, how statements use semicolons, and how to manage expression results and errors. Understand the evaluation order and proper nesting of symbols to write clearer, more effective Rust code.

We'll cover the following...

Let’s revisit our Hello World program and build up from there:

Rust 1.40.0
fn main() {
println!("Hello, world!");
}

The curly braces part is called a block. And as you’ve already seen in other examples, you’re not limited to just one println! macro call. You can have as many as you like:

Rust 1.40.0
fn main() {
println!("Hello, world!");
println!("Still alive!");
println!("I'm tired, good night!");
}

Exercise Comment out all three of the println! calls and see what happens.

Let’s look at another program:

Rust 1.40.0
fn main() {
let x: i32 = 4 + 5;
println!("4 + 5 == {}", x);
}

Just for kicks, I’m going to wrap the right-hand side of let x = in curly braces:

Rust 1.40.0
fn main() {
let x: i32 = { 4 + 5 };
println!("4 + 5 == {}", x);
}

What we’ve done here is create a new block, and put the expression 4 + 5 inside of it. Blocks themselves are expressions, and ...