Type assertions

A type assertion provides access to an interface value's underlying concrete value.

  1. t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

  1. t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

Note the similarity between this syntax and that of reading from a map.

type-assertions.go

  1. package main
  2. import "fmt"
  3. func main() {
  4. var i interface{} = "hello"
  5. s := i.(string)
  6. fmt.Println(s)
  7. s, ok := i.(string)
  8. fmt.Println(s, ok)
  9. f, ok := i.(float64)
  10. fmt.Println(f, ok)
  11. f = i.(float64) // panic
  12. fmt.Println(f)
  13. }