The Empty Interface
In this page:
What Is interface{}?
interface{} is an interface with no method requirements at all, which means literally every type in Go automatically satisfies it. It's how functions like fmt.Println can accept arguments of any type.
Example: What Is interface{}?
package main
import "fmt"
func describe(v interface{}) {
fmt.Printf("value: %v, type: %T\n", v, v)
}
func main() {
describe(42)
describe("hello")
describe(true)
}
Login to try C/C++/Java/PHP code in the editor
The any Alias
Since Go 1.18, any is a built-in alias for interface{}, introduced to make code that accepts arbitrary values easier to read, especially once generics also started using interfaces heavily for type constraints.
Note: Prefer any in new code -- it's identical to interface{} but reads more clearly.
Example: The any Alias
package main
import "fmt"
func printAny(v interface{}) {
fmt.Println("got:", v)
}
func main() {
printAny(3.14)
printAny([]int{1, 2, 3})
}
Login to try C/C++/Java/PHP code in the editor
A Heterogeneous Slice
Because interface{} accepts anything, it lets you build a slice that holds values of completely different types, something a normal typed slice like []int cannot do.
Example: A Heterogeneous Slice
package main
import "fmt"
func main() {
mixed := []interface{}{1, "two", 3.0, false}
for _, v := range mixed {
fmt.Println(v)
}
}
Login to try C/C++/Java/PHP code in the editor
- Overusing interface{} (or any) everywhere, throwing away Go's compile-time type checking when a specific type would do.
- Forgetting a type assertion or type switch is needed to actually use a value stored in an empty interface as its concrete type.
- Treating any and 'interface{}' as different things -- any is simply an alias for interface{} since Go 1.18.
- interface{} (aliased as any since Go 1.18) has zero method requirements, so every type satisfies it.
- It's used when a function truly needs to accept a value of any type, like fmt.Println's arguments.
- Getting the concrete value back out requires a type assertion or type switch.
- Overusing the empty interface sacrifices Go's compile-time type safety, so it should be used sparingly.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: