We have a few structs and we wanted to have a common ToMap
method that converts the struct to Map. It does by marshaling and unmarshalling to json. But it does not seem to work.
Is it because the Mappable
struct receives ToMap()
and it does not have any member attributes?
If so, is there any way to make ToMap()
to be received on Params
struct instead of Mappable
struct.
I've kept the code below but feel free to edit at https://play.golang.org/p/aDsYxddImxb too
package main
import (
"fmt"
"encoding/json"
)
type Mappable struct {}
func (m *Mappable) ToMap() (reqInterface map[string]interface{}) {
resJson, err := json.Marshal(m)
fmt.Println("**** err ****", err)
json.Unmarshal(resJson, &reqInterface)
return
}
type Params struct {
Mappable
A string `json:"a"`
B string `json:"b"`
C string `json:"c"`
D string `json:"d"`
}
func main() {
params := Params{
A: "dummy",
B: "dummy",
C: "dummy",
D: "dummy",
}
fmt.Printf("struct to convert: %#v \n", params)
fmt.Println("Converted with common ToMap method: ", params.ToMap())
}