Rust Variable Scope

In Rust, the scope of a variable is the region of the program where the variable is visible and accessible. A variable's scope is determined by where it's declared and where it's accessible in the code.

Here's an example of variable scope in Rust:

fn main() {
    let x = 5;  // variable x is declared in the main function

    {
        let y = 10;  // variable y is declared in a nested block
        println!("x: {}, y: {}", x, y);  // both x and y are visible and accessible
    }

    // y is not accessible here, because it was declared in a nested block
    println!("x: {}", x);  // x is still accessible here
}
Source‮i.www:‬giftidea.com

In this example, we're declaring a variable x in the main function with a value of 5. We're then creating a nested block using curly braces and declaring a variable y with a value of 10 inside that block. Both x and y are visible and accessible within that block, so we can print their values using the println! macro.

Once we exit the nested block, the variable y is no longer accessible, because it was declared inside that block. However, the variable x is still accessible outside the block, because it was declared in the main function.

It's important to note that Rust has strict rules for variable scope and ownership, which help prevent common bugs like use-after-free errors and data races. Rust's ownership model ensures that variables are always valid and that memory is never accessed after it has been freed. This makes Rust programs safer and more reliable than programs written in other languages.