Skip to content
Tutorials Center
My learning

Topics

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.

Go
var v any = 42
v = "now a string"

Try it

Go Holding different types

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.

Go Assertions and comparison

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

Go
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 any may allocate. In hot paths prefer generics.
  • any is not a wildcard type parameter. []any is not a []int; you cannot pass one where the other is expected. Convert elements one by one.
  • json.Unmarshal into any produces map[string]any, []any, float64, string, bool or nil. Numbers are always float64 unless you use Decoder.UseNumber.
  • Constraints. In a constraint position any means "no restriction"; it does not imply comparable, so == is not allowed on a type parameter constrained only by any.
  • fmt functions take ...any. That is why Println accepts everything and why go vet checks format strings.
  • Nil-interface trap. An any holding a nil pointer is not equal to nil. See Nil interface pitfall.
  • Prefer small interfaces. Declaring interface{ Name() string } documents what you need and keeps type safety.