You might have heard about type assertion and static conversion somewhere in other programming langauages. Here we are going to dive deep in Go.
Type Assertion:
In Go, type assertions are used to extract and test the dynamic type of an interface value. They allow you to determine if an interface value holds a specific underlying concrete type and obtain that value if it does. Here’s an example of how to use type assertions in Go:
package main
import "fmt"
func main() {
var x interface{}
x = 42 // x holds an int
// Type assertion to check if x holds an int and get its value.
if val, ok := x.(int); ok {
fmt.Printf("x is an int: %d\n", val)
} else {
fmt.Println("x is not an int")
}
// Attempting to access x as a string (which it isn't).
if val, ok := x.(string); ok {
fmt.Printf("x is a string: %s\n", val)
} else {
fmt.Println("x is not a string")
}
}
In this code, we use type assertion to check if x
holds an int
and print its value. We then attempt to assert it as a string
, which will fail.
Type assertions are commonly used when working with interfaces in Go, allowing you to safely access the concrete values within interface values while checking their compatibility.