DEV Community

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

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

1 1

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more