Golang为接口分配了一个地图

时间:2018-01-19 12:02:31

标签: go

我想将地图分配给基础值类型为map[string]interface的接口。

type Data struct{
  data interface{}
}

result := make(map[string]interface{})
data := Data{
   data:result
}

details := make(map[string]interface{})
details["CreatedFor"] = "dfasfasdf"
details["OwnedBy"] = "fasfsad"

如何将详细信息值插入data struct中的Data接口?

1 个答案:

答案 0 :(得分:1)

为了能够将界面视为地图,您需要先将其选中为地图。

我已经修改了您的示例代码以使其更清晰,内联注释解释了它的作用:

package main

import "fmt"

func main() {
    // Data struct containing an interface field.
    type Data struct {
        internal interface{}
    }

    // Assign a map to the field.
    type myMap map[string]interface{}
    data := Data{
        internal: make(myMap),
    }

    // Now, we want to access the field again, but as a map:
    // check that it matches the type we want.
    internalMap, ok := data.internal.(myMap)
    if !ok {
        panic("data.internal is not a map")
    }

    // Now what we have the correct type, we can treat it as a map.
    internalMap["CreatedFor"] = "dfasfasdf"
    internalMap["OwnedBy"] = "fasfsad"

    // Print the overall struct.
    fmt.Println(data)
}

输出:

{map[CreatedFor:dfasfasdf OwnedBy:fasfsad]}