Type assertion in Go Programming Language
Type assertion is a way to retrieve dynamic value from interface type value.
Example
package main
import (
"fmt"
"reflect"
)
func main() {
var anyType interface{}
anyType = "Canada"
fmt.Println("Variable type:", reflect.TypeOf(anyType))
str, ok := anyType.(string) // Type assertion form.
if ok {
fmt.Println("Variable type:", reflect.TypeOf(str))
} else {
fmt.Println("Variable is not String.")
}
var intType = 100
anyType = intType
fmt.Println("Variable type:", reflect.TypeOf(anyType))
var anotherType interface{}
anotherType = anyType
fmt.Println("Variable type:", reflect.TypeOf(anotherType))
}
Most Helpful This Week
Golang program for implementation of Longest Common Sub-sequence
GO language program with example of Array Reverse Sort Functions for integer and strings
How do you handle HTTP errors in Go?
What is an HTTP client in Go?
Creating Instances of Struct Types
How to initialize a struct containing a slice of structs in Golang?
How to access slice items in Golang?
How do you set headers in an HTTP response in Go?
GO language program with example of Sort Functions for integer, strings and float64 data type
Golang program for implementation of Median of Medians