Home > Backend Development > Golang > How Can I Perform Type Assertion on a Go `reflect.TypeOf()` Result?

How Can I Perform Type Assertion on a Go `reflect.TypeOf()` Result?

Patricia Arquette
Release: 2024-12-24 22:06:20
Original
339 people have browsed it

How Can I Perform Type Assertion on a Go `reflect.TypeOf()` Result?

Type Assertion Using reflect.TypeOf() in Go

In Go, when working with interfaces, it may be necessary to perform type assertion to obtain the underlying concrete type. The question arises regarding how to cast a Type (returned by reflect.TypeOf()) to a specific type for assertion.

Problem:

Consider the example code:

func IdentifyItemType(name string) interface{} {
    var item interface{}
    switch name {
    default:
        item = Article{}
    }
    return item
}
Copy after login

Here, we aim to identify a struct (Article) based on a string name. However, type assertion requires a type, but reflect.TypeOf() returns a Type.

Solution:

If the goal is to switch on the type of the outer interface{}, reflection is not necessary:

switch x.(type){
  case int: 
    dosomething()
}
Copy after login

However, to switch on the type of attributes within an interface, reflection can be employed:

s := reflect.ValueOf(x)
for i:=0; i<s.NumValues; i++{
  switch s.Field(i).Interface().(type){
    case int: 
      dosomething()
  }
}
Copy after login

This allows the switching of types on the attributes of the interface. While not an elegant solution, it provides functionality until a better alternative is discovered.

The above is the detailed content of How Can I Perform Type Assertion on a Go `reflect.TypeOf()` Result?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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