0
0
Goprogramming~10 mins

Short variable declaration in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Short variable declaration
Start
Use := to declare and assign
Variable created with type inferred
Variable ready to use
End
The short variable declaration uses := to create and assign a variable in one step, with Go inferring the type automatically.
Execution Sample
Go
package main
import "fmt"
func main() {
  x := 10
  fmt.Println(x)
}
This code declares a variable x with value 10 using short declaration and prints it.
Execution Table
StepCode LineActionVariable StateOutput
1x := 10Declare x and assign 10x = 10 (int)
2fmt.Println(x)Print value of xx = 10 (int)10
3EndProgram endsx = 10 (int)
💡 Program ends after printing the value of x
Variable Tracker
VariableStartAfter 1After 2Final
xundefined101010
Key Moments - 2 Insights
Why do we use := instead of = when declaring a variable?
The := operator both declares and assigns a variable in one step, as shown in execution_table step 1. Using = alone would require the variable to be declared first.
What type does the variable x have after declaration?
Go infers the type from the assigned value. In execution_table step 1, x is assigned 10, so its type is int.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x after step 1?
A10
Bundefined
C0
Dnil
💡 Hint
Check the 'Variable State' column in row for step 1 in execution_table
At which step is the variable x printed?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Code Line' and 'Action' columns in execution_table
If we replace := with = in line 1, what will happen?
AVariable x will be declared and assigned
BCompilation error because x is not declared
Cx will be assigned zero value
DProgram will print 0
💡 Hint
Recall that := declares and assigns, = only assigns to existing variables
Concept Snapshot
Short variable declaration uses := to declare and assign a variable in one step.
Go infers the variable type automatically from the assigned value.
Example: x := 10 declares x as int with value 10.
Use := only inside functions, not for package-level variables.
Trying to use = without prior declaration causes an error.
Full Transcript
This example shows how to use short variable declaration in Go. The := operator declares a variable and assigns a value at the same time. In the code, x := 10 creates an integer variable x with value 10. Then fmt.Println(x) prints the value 10. The execution table traces these steps clearly. The variable tracker shows x changes from undefined to 10 after declaration. Key moments clarify why := is needed and how Go infers types. The quiz tests understanding of variable state and declaration rules. This helps beginners see how short variable declaration works step-by-step.