Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 147 ยท Interfaces

The Empty Interface and any

Learn Go's empty interface and the any alias - storing mixed values, type assertions with the comma-ok form, type switches, JSON decoding into any, and why to avoid it.

An interface lists the methods a value must have. What if the list is empty? Then every type satisfies it, because every type has at least zero methods. That interface is written interface{} and is called the empty interface. Since Go 1.18 it also has a friendlier name, any, which is just an alias: any and interface{} mean exactly the same thing.

A variable of type any can hold an int, a string, a slice, a struct or a function. That makes it the right tool when you truly can't know the type in advance, such as fmt.Println accepting anything or json.Unmarshal decoding unknown documents. It also gives up the compiler's help, so you have to recover the concrete type yourself at run time. This lesson shows how to store and recover values, how type assertions and type switches work, how JSON decoding into any behaves, and when to reach for generics or real interfaces instead. It builds on Interfaces.

any holds anything

Assign any value to an any variable and it stores the value together with its type. A slice of any can mix types freely:

Go A slice of mixed values

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.

The values keep their real types: the 3.0 is a float64 and the array stays [2]int. Printing nil shows <nil> for both value and type, since an empty interface holding nothing has no dynamic type.

Many standard library functions use any because they must accept everything: fmt.Println(a ...any), json.Marshal(v any), sort.Slice(x any, ...), errors.As(err error, target any).

You can't use an any value directly

The flip side: the compiler knows only that an any is "something". You can't add, index or call methods on it without first saying what it is:

Go No operations on a bare any (fails on purpose)

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.

The compiler rejects this with invalid operation: operator + not defined on a (variable of interface type any). To use the number you have to get it out, and that is what type assertions are for.

Type assertions

A type assertion x.(T) says "I believe the interface value x holds a T; give it to me". With one result it panics when you are wrong. With two results, the comma-ok form, it never panics: you get the value and a boolean:

Go Type assertions and comma-ok (fails on purpose)

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.

When the assertion fails in comma-ok form, ok is false and the first result is the zero value of T. The last line panics with panic: interface conversion: interface {} is string, not int. The type name in that message is written interface {} (with a space) even if your code used any. Prefer the comma-ok form unless a mismatch would be a genuine programming error.

You can also assert to another interface type, to ask "does this value have that behavior?". Type Assertions and Type Switches covers that pattern in depth.

Type switches

When a value may be one of several types, a type switch is neater than a chain of assertions. The syntax switch v := x.(type) binds v with the matched type inside each case:

Go A type switch

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.

Inside a single-type case, v has that concrete type, so v*2 and v.Error() compile. In a case that lists several types (bool, rune) or in default, v keeps the original interface type. Cases are tried top to bottom, so an interface case such as error must come before anything it would swallow. Note that 'x' is a rune, which is int32, not int.

Common surprises with concrete types

An any stores the exact dynamic type, so look-alike types are different:

Go Exact types matter

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.

Two interface values are equal only when both their dynamic types and values are equal, so int(3) and int64(3) differ. Comparing interfaces whose dynamic type is a slice, map or function panics at run time with runtime error: comparing uncomparable type []int, which is why any is risky as a map key.

Decoding JSON into any

The best-known use of any is decoding JSON whose shape you don't know. encoding/json maps JSON values to a small fixed set of Go types: objects become map[string]any, arrays []any, strings string, numbers float64, booleans bool and null nil:

Go JSON into any

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.

Notice age arrives as float64, not int: every JSON number is a float64. All the assertions in the navigation line would panic if the document had a different shape. For documents whose structure you know, decode into a struct instead; you get types, field names and errors at decode time. Use any only for genuinely dynamic data, and prefer json.RawMessage when you want to postpone decoding a part.

Why you should usually avoid any

any is a way of turning off the type checker, and every use shifts bugs from compile time to run time. In everyday Go code you should prefer, in this order:

  1. A concrete type, when you know it.
  2. A small interface describing the behavior you need, such as io.Reader or fmt.Stringer.
  3. A generic function (see Generics), when the same algorithm works for many types and you need the type back.
  4. any, only when the data is truly open-ended.

Compare a function using any with a generic one:

Go any versus generics

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.

Notice what the any version costs: you can't pass []string where []any is expected (slices of different element types are different types), you must copy element by element, and the caller must assert. The generic version does none of that. Boxing a value into an interface also usually allocates memory, which matters in hot loops; Performance Tuning returns to this.

Be wary of APIs that take map[string]any or ...any for configuration. They compile with anything, then fail at run time. Use a struct or functional options instead (see Constructors, Options and Builders).

any versus other interfaces

any is just an interface with no methods, so everything you learned about interface values applies: it stores a dynamic type and value, it can be nil, and assigning a concrete value copies it. A related shortcut: since Go 1.18 the predeclared constraint comparable and any also appear in generics, where any as a constraint means "no restriction on T"; that is the same word with a related meaning, explained in Constraints and Type Sets.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the relationship between any and interface{}?

    Since Go 1.18, any is a predeclared alias for interface{}. They are interchangeable.
  2. 2. After var x any = "hi", what does n, ok := x.(int) produce?

    The comma-ok form never panics. A failed assertion returns the zero value of the target type and false.
  3. 3. Which type does json.Unmarshal use for a JSON number when decoding into any?

    By default every JSON number becomes a float64, so you must convert it yourself if you need an integer.
  4. 4. In switch v := x.(type) { case int, string: ... }, what is the type of v inside that case?

    With several types in one case, Go cannot pick one concrete type, so v keeps the type of the switch expression.
  5. 5. Why can you not pass a []string to a parameter of type []any?

    Each any element is a two-word interface value, while a string element is a different size. You must copy the elements into a new []any, or use generics.

Summary

  • any is an alias for interface{}; every type satisfies it, so it can hold any value.
  • You can't operate on an any directly: recover the type with an assertion or a type switch.
  • x.(T) panics on mismatch, while v, ok := x.(T) never panics.
  • A type switch handles many possible types; with multiple types in one case the variable stays an any.
  • Interface equality needs identical dynamic types, and comparing uncomparable ones panics.
  • JSON decoded into any gives map[string]any, []any, string, float64, bool and nil.
  • Prefer concrete types, small interfaces and generics; use any only for truly dynamic data.

Next: Type Assertions and Type Switches