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
Release: 2024-12-04 10:39:11
Original
1361 people have browsed it

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")
}
Copy after login

2. Extracting the String Representation of a Type:

Utilizing TypeName:

fmt.Println(reflect.TypeOf(w).Name())
Copy after login

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)
}
Copy after login

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")
}
Copy after login

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)
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template