Type assertions in Go help access the underlying type of an interface and remove ambiguity from an interface variable. In this post, we will get a closer look at type assertions.
What are type-assertions in Golang?
Type assertions reveal the concrete value inside the interface variable. Below is an example showing the assertion.
package main
import "fmt"
func main() {
var i interface{} = 42
//
fmt.Println(i.(int)) // 42
}
Type assertion syntax
The syntax for type assertion is simple. We take the interface variable and then access type with parenthesis as shown below.
// declare interface and assign
var i interface{} = "a string"
//type-assertion
valueOfI := i.(string) // "a string"
interfaceVariable.(type)
is the syntax.
Why use interfaces?
Interfaces are a type that can take any value. This creates ambiguity. Nothing can be told about that variable. Type assertion and type-switches helps to understand what kind of value it contains and what type it is.
Checking type-assertions
To check type assertions we can use the second return value for correctness. Here is how to use that.
package main
import "fmt"
func main() {
var i interface{} = 42
v, ok := i.(string)
if ok == false {
fmt.Println("Wrong type assertion!")
} else {
fmt.Println(v)
}
// Wrong type assertion!
fmt.Println(i.(int)) // 42
}
Type-assertions and panic
Whenever a wrong assertion occurs panic happens. Panic is an error that can’t be seen before.
package main
import "fmt"
func main() {
var i interface{} = 42
v := i.(string)
fmt.Println(v)
}
Why is it useful?
Type-assertions are useful to remove the ambiguity from interface variables. It helps unwrap the concrete value inside an interface variable.