Sobes.tech
Junior — Middle

How can the specific data type passed through the Any interface be determined?

sobes.tech AI

Answer from AI

In Go, to determine the specific data type passed through the interface{} (similar to Any), the following methods are used:

  • Type assertion: Checks and retrieves the value of a specific type from the interface.
var i interface{} = 42

// Type assertion with error handling
value, ok := i.(int)
if ok {
    fmt.Println("It's an int with value", value)
} else {
    fmt.Println("Not an int")
}
  • Type switch: Checks multiple types and executes corresponding code.
switch v := i.(type) {
case int:
    fmt.Println("int", v)
case string:
    fmt.Println("string", v)
default:
    fmt.Println("unknown type")
}
  • Reflection (reflect package): Used for more complex cases where the type is unknown in advance.
import "reflect"

func printType(i interface{}) {
    t := reflect.TypeOf(i)
    fmt.Println("Type of value:", t)
}

Most often, using type assertion or type switch is sufficient for determining the type passed through interface{}.