DEV Community

Cover image for Go Crash Course Part VI: Blocks, Scopes and Shadowing
Mofi Rahman
Mofi Rahman

Posted on • Updated on • Originally published at blogs.moficodes.dev

Go Crash Course Part VI: Blocks, Scopes and Shadowing

Blocks

In go a block is defined with a set of {}. Usually when we create a function we are in a block already. But we can define a block pretty much anywhere.

i := 10
{
    i := 5
    fmt.Println(i) // i is 5
}
fmt.Println(i) // i is 10
Enter fullscreen mode Exit fullscreen mode

Scope

Scope defines where certain variable would be defined in. A scope can be block scoped, function scoped or package scoped. Each scope encompasses the previous. A package scoped variable would be available to the function and block but not the other way around.

x := 10
var z int // z declared here
{
    fmt.Println(x) // this is fine
    y := 15
    z = 20 // defined here 
}
fmt.Println(y) // this is not fine
fmt.Println(z) // this is fine
Enter fullscreen mode Exit fullscreen mode

Shadowing

We can shadow any variable that is defined in the outer scope.

x := 10
{
    x := 15
    {
        x := 20
        fmt.Println(x) // 20
    }
    fmt.Println(x) // 15
}
fmt.Println(x) // 10
Enter fullscreen mode Exit fullscreen mode

Just block level shadowing is uncommon. There are rare use cases for this. But I haven't found really good use case for block level shadowing or even for blocks for that matter.

Next Steps

This is Part 6 of this Go crash course series.

Top comments (0)