When working with Go's versatile interface{} type, it's essential to navigate its inherent flexibility. To effectively utilize interface{}, we delve into your intriguing questions:
Type Switch to the Rescue:
switch v := w.(type) { case int: fmt.Println("Type: integer") case string: fmt.Println("Type: string") }
Utilizing TypeName:
fmt.Println(reflect.TypeOf(w).Name())
Type Assertion with TypeName:
typeName := reflect.TypeOf(w).Name() if typeName == "int" { value := w.(int) } else if typeName == "string" { value := w.(string) }
In your specific example, you can obtain the "real" type of w using a type switch:
switch w := weirdFunc(5).(type) { case int: fmt.Println("w is an integer") case string: fmt.Println("w is a string") }
Alternatively, you can leverage the reflect package to retrieve the type name itself:
typeName := reflect.TypeOf(w).Name() fmt.Println("w's type name:", typeName)
The above is the detailed content of How Can I Determine the Underlying Type of Go's `interface{}`?. For more information, please follow other related articles on the PHP Chinese website!