Variables have a scope, which is the place in the code that you are allowed to use them. The scope of a variable begins where it is created and extends to the end of the block along the way it is accessible from nested blocks. A block is a collection of statements inside curly braces that includes function bodies. In this example, x is defined in the main functions block. Then we create a nested block. Inside the nested block, we create y and then we print x and y which works just fine because x is accessible from nested blocks.
Then the block ends and why is immediately dropped at this point. There is no garbage collector values are always immediately dropped when they go out of scope, which means the last print won't work but fear not. We discover this at compile time. The error messages pretty clear cannot find value y in this scope, so we would either need to hoist the second print line macro up into the same scope as y, or move y down to the same scope as the second print line macro variables can also be shadowed. Another way to think about shadowing is the variables are always local to their scope. Here we create a variable x and initialize it to five in the outer block.
Then in the inner block x is shadowed with a new value 99. These two x's are different variables with different values, they just overlap in scope. The first print we'll see x as 99. Note that the value of the first x is not accessible from the inner block after it is shadowed. But as soon as the inner block ends, the inner x is dropped and the outer x is once again accessible so the last print sees the value five. You can also shadow variables in the same scope.
Here we shadow a mutable variable x with an immutable variable x that we initialize to the first access value. This essentially redefines the variable x with different mutability, even cooler, the compiler will often optimize away this actual operation. And so nothing actually happens in the assembly code. You can even shadow a variable to a different type in the same scope, which some people like to do and data transformation pipelines that discard intermediate representations. So in this example, meme starts as the words more cowbell and then becomes an image. In the next video, we'll go over memory, safety.