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
What is the default HTTP server in Go?
How to add items to Slice using append function in Golang?
Web Application to generate QR code in Golang
How do you handle HTTP redirects in Go?
Program to print full pyramid using star
Golang program for implementation of Rabin-Karp
GO language program with an example of Hash Table
Struct Instantiation using new keyword
Golang program for drawing a Cuboid
Write string slice line by line to a text file