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.
s, ok := value.(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
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
xis nil, the assertion always fails, even to an interface type, sookis false or the program panics.
Usage notes
- The assertion is about the dynamic type. A named type and its underlying type are different, and
*Tis notT. - Asserting to an interface checks the method set at run time. That is the standard way to test for optional behavior, as
io.WriterToorfmt.Stringerchecks 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.Asover a manual assertion on errors, since it also looks through wrapped errors. See errors.As(). - Overusing
anyand 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 anintfails; it does not convert the number. - Cost is small: comparing a type pointer for concrete types, and a cached lookup for interface targets.