golang type assertion using reflect.Typeof()

dorajistyle picture dorajistyle · Jan 12, 2015 · Viewed 22.6k times · Source

I've tried to identify a struct with string value(name). reflect.TypeOf returns Type.

But type assertion needs a type.

How can I casting Type to type?

Or any suggestion to handle it?

http://play.golang.org/p/3PJG3YxIyf

package main

import (
"fmt"
"reflect"
)
type Article struct {
    Id             int64       `json:"id"`
    Title          string      `json:"title",sql:"size:255"`
    Content        string      `json:"content"`
}


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

func main() {

    i := IdentifyItemType("name")
    item := i.(Article)
    fmt.Printf("Hello, item : %v\n", item)
    item2 := i.(reflect.TypeOf(i))  // reflect.TypeOf(i) is not a type
    fmt.Printf("Hello, item2 : %v\n", item2)

}

Answer

MondayPaper picture MondayPaper · Sep 2, 2015

If you need to switch on the type of the outer interface{} you wont need reflection.

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

...but if you need to switch on the type of the attributes in an interface then you can do this:

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

I haven't found a cleaner way, I'd love to know if it exists.