Type assertion and type switch


Sometimes, you may want to know the exact type of an interface variable. In this scenario, you can use type assertion:

  1. x.(T)

x is the variable whose type must be interface, and T is the type which you want to check. For example:

  1. package main
  2. import "fmt"
  3. func printValue(v interface{}) {
  4. fmt.Printf("The value of v is: %v", v.(int))
  5. }
  6. func main() {
  7. v := 10
  8. printValue(v)
  9. }

The running result is:

  1. The value of v is: 10

In the above example, using v.(int) to assert the v is int variable.

if the type assertion operation fails, a running panic will occur: change

  1. fmt.Printf("The value of v is: %v", v.(int))

into:

  1. fmt.Printf("The value of v is: %v", v.(string))

Then executing the program will get following error:

  1. panic: interface conversion: interface is int, not string
  2. goroutine 1 [running]:
  3. panic(0x4f0840, 0xc0820042c0)
  4. ......

To avoid this, type assertion actually returns an additional boolean variable to tell whether this operations holds or not. So modify the program as follows:

  1. package main
  2. import "fmt"
  3. func printValue(v interface{}) {
  4. if v, ok := v.(string); ok {
  5. fmt.Printf("The value of v is: %v", v)
  6. } else {
  7. fmt.Println("Oops, it is not a string!")
  8. }
  9. }
  10. func main() {
  11. v := 10
  12. printValue(v)
  13. }

This time, the output is:

  1. Oops, it is not a string!

Furthermore, you can also use type switch which makes use of type assertion to determine the type of variable, and do the operations accordingly. Check the following example:

  1. package main
  2. import "fmt"
  3. func printValue(v interface{}) {
  4. switch v := v.(type) {
  5. case string:
  6. fmt.Printf("%v is a string\n", v)
  7. case int:
  8. fmt.Printf("%v is an int\n", v)
  9. default:
  10. fmt.Printf("The type of v is unknown\n")
  11. }
  12. }
  13. func main() {
  14. v := 10
  15. printValue(v)
  16. }

The running result is here:

  1. 10 is an int

Compared to type assertion, type switch uses keyword type instead of the specified variable type (such as int) in the parentheses.

References:
Effective Go;
Go – x.(T) Type Assertions;
How to find a type of a object in Golang?.