我如何从 map[string] MyStruct 转换为 map[string] MyInterface
How do i convert from map[string] MyStruct to map[string] MyInterface
当 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]
当 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]