将接口{}转换为Golang中的map

Sam*_*ech 16 reflection dictionary interface go

我正在尝试创建一个可以接受以下的功能

*struct
[]*struct
map[string]*struct
Run Code Online (Sandbox Code Playgroud)

这里struct可以是任何结构,而不仅仅是特定结构.将接口转换为*struct[]*struct正常工作.但给地图错误.

反映后显示它是map [],但在尝试迭代范围时给出错误.

这是代码

package main

import (
    "fmt"
    "reflect"
)

type Book struct {
    ID     int
    Title  string
    Year   int
}

func process(in interface{}, isSlice bool, isMap bool) {
    v := reflect.ValueOf(in)

    if isSlice {
        for i := 0; i < v.Len(); i++ {
            strct := v.Index(i).Interface()
            //... proccess struct
        }
        return
    }

    if isMap {
        fmt.Printf("Type: %v\n", v)     // map[]
        for _, s := range v {           // Error: cannot range over v (type reflect.Value)
            fmt.Printf("Value: %v\n", s.Interface())
        }
    }    
}

func main() {
    b := Book{}
    b.Title = "Learn Go Language"
    b.Year = 2014
    m := make(map[string]*Book)
    m["1"] = &b

    process(m, false, true)
}
Run Code Online (Sandbox Code Playgroud)

有没有办法转换interface{}为map并迭代或获取它的元素.

Cer*_*món 27

如果map值可以是任何类型,则使用reflect迭代地图:

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

操场的例子

如果有一组很小且已知的结构类型,则可以使用类型开关:

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
   }
}
Run Code Online (Sandbox Code Playgroud)


cni*_*tar 21

你不需要在这里反思.尝试:

v, ok := in.(map[string]*Book)
if !ok {
    // Can't assert, handle error.
}
for _, s := range v {
    fmt.Printf("Value: %v\n", s)
}
Run Code Online (Sandbox Code Playgroud)

您的其余功能也是如此.当你通过类型开关更好地服务时,看起来你正在使用反射.


或者,如果你坚持在这里使用反射(这没有多大意义),你也可以使用Value.MapKeysValueOf的结果(参见答案/sf/answers/2673024021/)


Vik*_*wal 7

这可能会有所帮助:

b := []byte(`{"keyw":"value"}`)

var f interface{}
json.Unmarshal(b, &f)

myMap := f.(map[string]interface{})

fmt.Println(myMap)
Run Code Online (Sandbox Code Playgroud)