Variable Scope
Start with Go Variable Scope
Scope determines where a variable name can be used. Go has package scope and nested local scopes created by function bodies and blocks.
What you’ll learn
- Identify nested lexical scopes.
- Explain shadowing with :=.
- Choose assignment when modifying the outer variable.
Understand the idea
A variable declared inside a function is not visible outside it. Variables introduced inside if or for blocks are limited to the appropriate scope. A short declaration inside a nested block can create a new variable with the same name as an outer one; this is called shadowing.
Shadowing is legal but can confuse readers when two variables look identical. Use deliberate names and avoid accidental := in inner blocks when your intention is to update an outer variable.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
message := "outside"
if true {
message := "inside"
fmt.Println("Block:", message)
}
fmt.Println("Function:", message)
}
Output
Block: inside
Function: outsideTrace what the program does
The message := "inside" declaration creates a distinct variable inside the if block. Printing there shows inside. When that block ends, the outer message is still outside, so the next print shows outside.
Avoid common mistakes
- Shadowing can happen with
:=inside a new block even when the same name exists outside. - Do not assume a variable declared inside a block remains accessible after the closing brace.
Try it yourself
Replace the inner declaration with message = "inside". Predict how both lines of output change and explain why.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go Variable Scope in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.