· 2 min read

Golang Notes — Type Assertion

This article was auto-translated from Chinese. Some nuances may be lost in translation.

In golang, for values of type interface{}, you can use a type assertion to assert that the interface holds a specific concrete type. This allows you to access the underlying value and call methods defined on that type.

var i interface{} = "hello"
s := i.(string)
fmt.Println(s)

This snippet asserts the original interface{} as a string.

However, note that if the underlying type is not a string, this code will panic immediately.

args := []interface{}{
		1,
		"1",
		"2",
	}
for _, arg := args {
  val := arg.(int) // interface conversion: interface {} is string, not int
  fmt.Println(val)
}

Golang provides a mechanism where a type assertion can return two values: the converted value, and a boolean indicating whether the assertion was successful.

args := []interface{}{
		1,
		"1",
		"2",
	}
for _, arg := args {
  if val, ok := arg.(int); ok {
    fmt.Println(val)    
  } else {
    fmt.Println("not int.")
  }
}

At this point, there are two key takeaways to keep in mind:

  1. Without the second return value, your program may panic if the assertion fails, unless you are absolutely sure of the type.
  2. Checking the second return value prevents the program from raising a panic.

Although it takes a bit more boilerplate, it is always safer to use the two-value form.

Another thing to note is that when the assertion fails, val will be the zero-value of the asserted type.

When the assertion fails, val will be the zero-value of the asserted type.

for _, arg := range args {
  if val, ok := arg.(int); ok {
    fmt.Println(val, ok) // 1, true
  } else {
    fmt.Println(val, ok) // 0 , false
    // 0, false
  }
}

Generally speaking, you rarely need to use this value after an assertion fails, but careless handling could still lead into a trap.

Related Posts

Explore Other Topics