How to convert interface{} to map

后端 未结 3 517
慢半拍i
慢半拍i 2021-01-31 08:43

I am trying to create a function that could accept following

*struct
[]*struct
map[string]*struct

Here struct could be any struct not just a sp

3条回答
  •  迷失自我
    2021-01-31 09:16

    If the map value can be any type, then use reflect to iterate through the map:

    if v.Kind() == reflect.Map {
        for _, key := range v.MapKeys() {
            strct := v.MapIndex(key)
            fmt.Println(key.Interface(), strct.Interface())
        }
    }
    

    playground example

    If there's a small and known set of struct types, then a type switch can be used:

    func process(in interface{}) {
      switch v := in.(type) {
      case map[string]*Book:
         for s, b := range v {
             // b has type *Book
             fmt.Printf("%s: book=%v\n" s, b)
         }
      case map[string]*Author:
         for s, a := range v {
             // a has type *Author
             fmt.Printf("%s: author=%v\n" s, a)
         }
       case []*Book:
         for i, b := range v {
             fmt.Printf("%d: book=%v\n" i, b)
         }
       case []*Author:
         for i, a := range v {
             fmt.Printf("%d: author=%v\n" i, a)
         }
       case *Book:
         fmt.Ptintf("book=%v\n", v)
       case *Author:
         fmt.Printf("author=%v\n", v)
       default:
         // handle unknown type
       }
    }
    

提交回复
热议问题