gpt4 book ai didi

dictionary - 我如何从 map[string] MyStruct 转换为 map[string] MyInterface

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

当 MyStruct 实现 MyInterface 时,如何将 map[string] MyStruct 转换为 map[string] MyInterface。

type MyInterface interface {
Say() string
}

var MyInterfaceMap map[string] MyInterface

type MyStruct struct{
Message string
}

func (myStruct *MyStruct) Say() string{
return myStruct.Message
}

func Init() {
data := []byte(`{"greet":{"Message":"Hello"}}`)
myStructMap := make(map[string] MyStruct )
_ = json.Unmarshal( data, &myStructMap)
MyInterfaceMap = myStructMap
}

最佳答案

解码后,将映射复制到 MyInterfaceMap,如下所示

package main

import (
"encoding/json"
"fmt"
"reflect"
)

type MyInterface interface {
Say() string
}

var MyInterfaceMap map[string]MyInterface

type MyStruct struct {
Message string
}

func (myStruct *MyStruct) Say() string {
return myStruct.Message
}

func main() {
data := []byte(`{"greet":{"Message":"Hello"}}`)
myStructMap := make(map[string]MyStruct)
err := json.Unmarshal(data, &myStructMap)
if err != nil {
panic(err)
}

MyInterfaceMap = make(map[string]MyInterface)
for k, v := range myStructMap {
MyInterfaceMap[k] = &v
}
fmt.Println(reflect.TypeOf(MyInterfaceMap))
fmt.Println(MyInterfaceMap)
}

结果是

map[string]main.MyInterface
map[greet:0x1050c1a0]

关于dictionary - 我如何从 map[string] MyStruct 转换为 map[string] MyInterface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49137828/

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