learn-rust

Free Rust 🦀 course in English 🇬🇧

View on GitHub

Table of Contents📚

Code Blocks🟪

What is a code block❓

A code block is a piece of code between two {} that is kind of isolated from the rest of the code, but it can still access variables and functions from outside the code block.

Usage

For example, we can use a code block to define and print a variable:

let sock1 = "First sock 🧦";

{
    let sock2 = "Second sock 🧦";
    println!("I have the {} and the {}", sock1, sock2);
}

Output:

I have the First sock 🧦 and the Second sock 🧦

Everything is working as expected, but now, let’s try to print the values of sock1 and sock2 outside the code block:

let sock1 = "First sock 🧦";

{
    let sock2 = "Second sock 🧦";
}

println!("I have the {} and the {}", sock1, sock2);

Output:

We get the following error because sock2 is not defined outside the code block

So the second sock disappears when the code block ends.


Home 🏠 - Next Section ⏭️


Course created by SkwalExe and inspired by Dcode