liveBook · Manning

Empty interface

As explained in Go in Practice, Second Edition

any is a predeclared Go type alias for the empty interface type interface{}, allowing values of any type.

An empty interface has no required methods, so a value of any Go type can satisfy it. `any` is an alias for `interface{}`; the two spellings are interchangeable. This makes an empty interface useful when values may have different types or a data structure is not known ahead of time. section 3.3 section 11.3

For example, a `[]interface{}` can hold values of different types. The flexibility has a cost: before using a value as a particular type, code generally must determine what type it contains. If a function can return one concrete type instead, that usually keeps its callers and tests simpler. section 3.3

Decode JSON with an unknown structure

```go package main import ( "encoding/json" "fmt" ) func main() { data := []byte(`{"firstName":"Jean","children":["Timothy","Jane"]}`) var value interface{} if err := json.Unmarshal(data, &value); err != nil { fmt.Println(err) return } object := value.(map[string]interface{}) fmt.Println(object["firstName"]) switch children := object["children"].(type) { case []interface{}: for _, child := range children { fmt.Println(child) } } } ``` Decoding into `interface{}` avoids defining a struct for the JSON shape. It does not make fields directly accessible: the example first asserts that the top-level value is a map, then inspects the array value with a type switch. section 11.3

Use this flexibility deliberately. Empty interfaces provide no constraint on which types a caller may pass, so mistaken assumptions can become runtime failures. For reusable code that must accept only a defined set of types, a generic type constraint offers guardrails that `interface{}` does not. section 3.4

How Go in Practice, Second Edition covers it

How deep it goes
Defines the zero-method interface and works through JSON decoding and type inspection, while identifying its lack of type constraints.
Examples
Shows an integer-filled `[]interface{}` shuffle slice and JSON decoded into values accessed through `map[string]interface{}`.
What it assumes
Builds on Go slices and structs while explaining what an interface with no required methods accepts.
What you can do after
Apply it via `encoding/json` to decode unknown JSON structures and inspect values with type assertions or switches.
How it connects
Connects heterogeneous slices and JSON decoding with type assertions, type switches, and generic type constraints.

Also explained in

Compare how 4 books explain empty interface →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.