Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Operators

Type assertions: x.(T)

Reference for Go type assertions x.(T): extracting the concrete value from an interface, the comma-ok form, asserting to another interface and panics.

A type assertion x.(T) looks inside an interface value x and checks whether it holds a value of type T. If T is a concrete type, the assertion succeeds when the dynamic type of x is exactly T, and returns that value. If T is an interface type, it succeeds when the dynamic value implements T, and returns the value as a T.

The single-result form panics on failure; the comma-ok form v, ok := x.(T) reports failure through ok instead. Use it whenever the type is not guaranteed.

Go
s, ok := value.(string)

Try it

Go Checked and unchecked assertions

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 Asserting to an interface

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
v := x.(T)
v, ok := x.(T)
Name Description
x An expression of interface type (including any). It cannot be a non-interface value.
T A concrete type, or an interface type. If T is concrete, it must implement the type of x, otherwise the compiler rejects the assertion as impossible.
v The value, of static type T.
ok true if the assertion held. On failure v is the zero value of T.

Panics

  • A failed single-result assertion panics with a *runtime.TypeAssertionError, whose message reads like "interface conversion: interface {} is string, not int".
  • If x is nil, the assertion always fails, even to an interface type, so ok is false or the program panics.

Usage notes

  • The assertion is about the dynamic type. A named type and its underlying type are different, and *T is not T.
  • Asserting to an interface checks the method set at run time. That is the standard way to test for optional behavior, as io.WriterTo or fmt.Stringer checks in the standard library do.
  • For checking several types in one place, a type switch is cleaner than a chain of comma-ok assertions.
  • Prefer errors.As over a manual assertion on errors, since it also looks through wrapped errors. See errors.As().
  • Overusing any and assertions gives up compile-time checking. Generics or small interfaces are often a better design.
  • A type assertion is not a conversion: x.(float64) on an interface holding an int fails; it does not convert the number.
  • Cost is small: comparing a type pointer for concrete types, and a cached lookup for interface targets.