Search code examples
dictionarygoassert

How do i convert from map[string] MyStruct to map[string] MyInterface


How do i convert from map[string] MyStruct to map[string] MyInterface, when MyStruct implements 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 
}

Solution

  • Once unmarshalled, copy the map to MyInterfaceMap like below

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

    And the result would be

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