Simple ways to check types in golang. The last one with swtich statement is the most useful for complex types.
fmt
packagepackage main
import "fmt"
func main() {
x := 10
fmt.Printf("Type of x is %T\n", x) // Output: Type of x is int
}
reflect
packagepackage main
import (
"fmt"
"reflect"
)
func main() {
x := 10
fmt.Println(reflect.TypeOf(x)) // Output: int
}
package main
import "fmt"
func main() {
var i interface{} = "hello"
if s, ok := i.(string); ok {
fmt.Println("i is a string:", s)
} else {
fmt.Println("i is not a string")
}
}
package main
import "fmt"
func main() {
var i interface{} = 10
switch i.(type) {
case int:
fmt.Println("i is an int")
case string:
fmt.Println("i is a string")
default:
fmt.Println("i is of unknown type")
}
}