0

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

siliconsenthil
  • 1,380
  • 1
  • 14
  • 25
  • There is no inheritance and virtual methods in Go. `Mappable.ToMap()` always receives a value of `*Mappable` regardless of where it's embedded. "Childs" don't automatically know about their "parents", you have to take care of that manually. In your case it's easier to just create a utility _function_ instead of a _method_, which may take an `interface{}` value and do what your `Mappable.ToMap()` does. – icza Sep 30 '19 at 07:20
  • 1
    Just in case it is not clear what icza means by `utility function`: A function with the signature `func ToMap(s interface{}) (reqInterface map[string]interface{})`. But I'd strongly suggest to first embrace go's intentional lack of inheritance (and this far also of generics) and learn how to write idiomatic Go code. Actually I doubt there is a good reason for a `ToMap` function at all. You are throwing away Go's type system instead of using it. – TehSphinX Sep 30 '19 at 10:54

0 Answers0