← Back to Go Course | Chapter 7: Interfaces | Lesson 2 of 7

The Empty Interface

The empty interface, interface{}, is a box shaped to hold absolutely anything, because it demands zero specific abilities to fit inside it.

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{}?

markup
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)
}

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

markup
package main

import "fmt"

func printAny(v interface{}) {
	fmt.Println("got:", v)
}

func main() {
	printAny(3.14)
	printAny([]int{1, 2, 3})
}

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

markup
package main

import "fmt"

func main() {
	mixed := []interface{}{1, "two", 3.0, false}
	for _, v := range mixed {
		fmt.Println(v)
	}
}
Common Mistakes
  1. Overusing interface{} (or any) everywhere, throwing away Go's compile-time type checking when a specific type would do.
  2. Forgetting a type assertion or type switch is needed to actually use a value stored in an empty interface as its concrete type.
  3. Treating any and 'interface{}' as different things -- any is simply an alias for interface{} since Go 1.18.
Chapter Summary
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.