Home >Backend Development >Golang >How Can I Determine the Underlying Type of Go's `interface{}`?

How Can I Determine the Underlying Type of Go's `interface{}`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 10:39:111380browse

How Can I Determine the Underlying Type of Go's `interface{}`?

Unveiling the True Nature of interface{}: Comprehensive Guide for Type Determination

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:

1. Unveiling the "Real" Type of w:

Type Switch to the Rescue:

switch v := w.(type) {
  case int:
    fmt.Println("Type: integer")
  case string:
    fmt.Println("Type: string")
}

2. Extracting the String Representation of a Type:

Utilizing TypeName:

fmt.Println(reflect.TypeOf(w).Name())

3. Converting a Value Using the String Representation of a Type:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn