0
0
Goprogramming~10 mins

Variable declaration using var in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Variable declaration using var
Start
Declare variable with var
Assign default zero value
Use variable in code
End
The program starts by declaring a variable using var, which assigns a default zero value. Then the variable can be used in the code.
Execution Sample
Go
package main
import "fmt"
var x int
func main() {
  fmt.Println(x)
}
Declares an integer variable x using var and prints its default value 0.
Execution Table
StepActionVariableValueOutput
1Declare variable x with varx0 (default int)
2Enter main functionx0
3Print xx00
4Program endsx0
💡 Program ends after printing the default value of x which is 0.
Variable Tracker
VariableStartAfter DeclarationAfter PrintFinal
xundefined000
Key Moments - 2 Insights
Why does x have the value 0 even though we didn't assign anything?
In Go, when you declare a variable with var but don't assign a value, it automatically gets the zero value for its type. See execution_table step 1 where x is set to 0.
Can we use x before declaring it with var?
No, variables must be declared before use. The execution_table shows declaration happens first (step 1) before printing (step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x right after declaration?
Aundefined
B1
C0
Dnil
💡 Hint
Check execution_table row 1 under Value column.
At which step does the program print the value of x?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look for the step with Action 'Print x' in execution_table.
If we change var x int to var x string, what would be the default value of x?
A"" (empty string)
B0
Cnil
Dundefined
💡 Hint
Recall Go assigns zero value based on type; for string it's empty string.
Concept Snapshot
var declares a variable with a type.
If no value assigned, Go sets zero value by type.
Example: var x int sets x to 0.
Use variable after declaration.
Zero values: int=0, string="", bool=false.
Full Transcript
This example shows how to declare a variable in Go using var. When you write var x int, Go creates x as an integer variable and sets it to 0 automatically because no value was assigned. The program then prints x, showing 0. Variables must be declared before use. Different types have different zero values, like empty string for string type. This helps avoid errors from uninitialized variables.