Go's duck typing: implicitly satisfied contracts.
The Empty Interface (any)
The interface with zero methods is satisfied by every type. It used to be
spelled interface{}; since Go 1.18 you can write the alias any instead.
They're identical.
var x any = 42
x = "now a string"
x = []int{1, 2, 3}
Use any when you genuinely don't know the type at compile time — JSON decoding,
generic containers (before generics existed), fmt.Println(x ...any), etc.
Getting the value back out
An any value is a box containing both a type and a value. To use it, you need
to "open the box" — with a type assertion or a type switch.
go playground
Loading...
When to reach for any
Use any sparingly. If you find yourself with any everywhere:
- For "either A or B" you usually want a struct or interface, not
any. - For "any printable thing" you want
fmt.Stringer. - For "container of T" you want generics (chapter 13).
- For "decode unknown JSON" you want
map[string]any— that's fine, but try to unmarshal into a struct as soon as you know the shape.
Are `any` and `interface{}` different types?