Go Reference ยท Built-in Types
The Go any type
Reference for Go any: the predeclared alias for interface{}, what it can hold, type assertions and switches, comparison rules and when to avoid it.
any is a predeclared alias for interface{}, the interface with no methods. Every type satisfies it, so a variable of type any can hold a value of any type. It was added in Go 1.18 together with generics, and the two spellings are completely interchangeable.
An any value stores two things: the dynamic type and the value. To use the value you must find out its type again with a type assertion or a type switch. Because this skips compile-time checking, prefer concrete types, interfaces with methods, or generics when you can.
var v any = 42 v = "now a string"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
var v any // nil interface v = value // any value is assignable t, ok := v.(T) // checked assertion t := v.(T) // panics if v does not hold a T switch x := v.(type) {} // type switch
| Part | Description |
|---|---|
any |
Same as interface{}; identical types, no conversion needed. |
v.(T) |
Asserts that the dynamic type is T (or implements interface T). |
nil |
The zero value of any, holding no type and no value. |
Edge cases: a failing one-result assertion panics with a message naming both types. Comparing two any values with == panics if their dynamic types are identical and not comparable (slices, maps, functions).
Usage notes
- Boxing costs. Storing a non-pointer value in an
anymay allocate. In hot paths prefer generics. anyis not a wildcard type parameter.[]anyis not a[]int; you cannot pass one where the other is expected. Convert elements one by one.json.Unmarshalintoanyproducesmap[string]any,[]any,float64,string,boolornil. Numbers are alwaysfloat64unless you useDecoder.UseNumber.- Constraints. In a constraint position
anymeans "no restriction"; it does not implycomparable, so==is not allowed on a type parameter constrained only byany. fmtfunctions take...any. That is whyPrintlnaccepts everything and whygo vetchecks format strings.- Nil-interface trap. An
anyholding a nil pointer is not equal tonil. See Nil interface pitfall. - Prefer small interfaces. Declaring
interface{ Name() string }documents what you need and keeps type safety.