mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

Go - Empty Interface

An empty interface is the interface type that specifies 0 elements.

go
// Empty interface.
interface{}

All types implement the empty interface.

go
var i interface{} // nil

// An empty interface may hold values of any type.
i = 10         // int
i = "Hello"    // string
i = true       // bool
i = []string{} // []string
i = struct{}{} // struct {}

The empty interface is used by code that handles values of unknown type.

go
// A function that accepts an argument of unknown type.
func PrintValue(v interface{}) {
  fmt.Printf("Value: %v\n", v)
}

// Can be called with any argument type.
PrintValue(100)
PrintValue("Go")
PrintValue([]int{1, 2, 3, 4})

Any

The predeclared type any is an alias for the empty interface interface{} (Added in Go v1.18).

go
var i any         // nil
// Equivalent to
var i interface{} // nil