Empty Interfaces and any
Start with Empty Interfaces and any
The predeclared identifier any is an alias for interface{}, the interface with no required methods.
What you’ll learn
- Explain the main purpose of empty interfaces and any.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Every Go value satisfies an empty interface, so var v any can hold an integer, string or struct. When you retrieve the value, the compiler still needs a concrete type for type-specific operations.
Use any when an API genuinely handles diverse types, such as generic formatting or decoding. Prefer specific parameter types and interfaces when the behavior is known; otherwise mistakes can appear only at runtime.
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 display(value any) {
fmt.Printf("%T: %v\n", value, value)
}
func main() {
display(42)
display("Go")
display(true)
}
Output
int: 42
string: Go
bool: trueTrace what the program does
The same function accepts three different concrete types. The %T format verb prints each dynamic type, while %v prints the value.
Avoid common mistakes
- any provides no methods of its own for performing type-specific operations.
- Using any everywhere forfeits useful compile-time type checking.
Try it yourself
Call display with a float64 and a small struct, and predict what %T will print.
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 Empty Interfaces and any 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.