gpt4 book ai didi

Golang 将映射分配给接口(interface)

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:51 26 4
gpt4 key购买 nike

我想将一个映射分配给一个接口(interface),其中基础值是 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 结构中的 data 接口(interface)?

最佳答案

为了能够将界面视为 map ,您需要先将其作为 map 进行类型检查。

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

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]}

关于Golang 将映射分配给接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48340687/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com