Essential Go  Edit on GitHub      File Issue

Empty interface

Technically speaking, an empty interface (interface{}) is an interface with no methods.

What follows from that is that every type conforms to interface{}.

In practice, empty interface is Go’s version of object type in Java or C# in that it combines a type and its value.

Empty interface is effectively a dynamic type in a static language.

Empty interface is also a way to implement union types in Go.

Since every type conforms to interface{}, you can assign any value to a variable of interface{} type.

At that point, you can no longer tell what is the real type at compile time.

You can query the type at runtime using:

Zero value of empty interface is nil.

Basic example:

func printVariableType(v interface{}) {
	switch v.(type) {
	case string:
		fmt.Printf("v is of type 'string'\n")
	case int:
		fmt.Printf("v is of type 'int'\n")
		// generic fallback
		fmt.Printf("v is of type '%T'\n", v)

func main() {
	printVariableType("string") // string
	printVariableType(5)        // int
	printVariableType(int32(5)) // int32
v is of type 'string'
v is of type 'int'
v is of type 'int32'
  ↑ ↓ to navigate     ↵ to select     Esc to close