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 Radix Sort
Illustration of Cigarette Smokers Problem in Golang
Golang program for implementation of Tower of Hanoi Algorithm
How do you catch panic in Golang?
Golang program for implementation LZW Data Compression and Uncompression
How to Convert string to float type in Go?