0
0
Goprogramming~10 mins

Empty interface in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Empty interface
Declare empty interface variable
Assign any value to variable
Use variable as any type
Type assertion or reflection to get original type
End
An empty interface variable can hold any value. You assign values, then use type assertion to get the original type.
Execution Sample
Go
package main

import "fmt"

func main() {
    var x interface{}
    x = 42
    fmt.Println(x)
    x = "hello"
    fmt.Println(x)
}
This code shows an empty interface variable holding an int, then a string, printing both.
Execution Table
StepActionVariable xOutput
1Declare x as empty interfacenil
2Assign 42 to x42 (int)
3Print x42 (int)42
4Assign "hello" to x"hello" (string)
5Print x"hello" (string)hello
💡 Program ends after printing both values.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
xnil42 (int)"hello" (string)"hello" (string)
Key Moments - 2 Insights
Why can variable x hold both an int and a string?
Because x is declared as an empty interface, it can hold any type. See execution_table steps 2 and 4 where x changes type.
What happens if you try to use x as a specific type without assertion?
You must use type assertion to convert x back to its original type. Without it, Go won't know the actual type stored in x.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x after step 2?
A"hello" (string)
B42 (int)
Cnil
D0
💡 Hint
Check the 'Variable x' column at step 2 in the execution_table.
At which step does x hold a string value?
AStep 1
BStep 2
CStep 4
DStep 3
💡 Hint
Look at the 'Variable x' column in execution_table for string values.
If you want to get the int value from x after step 2, what must you do?
AUse type assertion to int
BDirectly use x as int
CConvert x to string
DAssign x to a new variable without assertion
💡 Hint
Refer to key_moments about type assertion necessity.
Concept Snapshot
Empty interface in Go is written as interface{}.
It can hold any type of value.
Assign any value to it without error.
To use the stored value as its original type, use type assertion.
Useful for generic containers or functions.
Full Transcript
This visual execution shows how an empty interface variable x in Go can hold any type of value. Initially, x is declared with no value (nil). Then, x is assigned the integer 42 and printed, showing 42. Next, x is assigned the string "hello" and printed, showing hello. The variable tracker shows x changing from nil to 42 (int) to "hello" (string). Key moments explain that the empty interface allows any type and that type assertion is needed to use the stored value as its original type. The quiz questions check understanding of the variable's value at different steps and the need for type assertion. This helps beginners see step-by-step how empty interfaces work in Go.