I have the following:
https://play.golang.org/p/ADX6H-bh0CU
package main
import (
"encoding/xml"
"fmt"
)
type xmlMap map[string]string
type xmlMapEntry struct {
XMLName xml.Name
Value string `xml:",chardata"`
}
func (m xmlMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if len(m) == 0 {
return nil
}
err := e.EncodeToken(start)
if err != nil {
return err
}
for k, v := range m {
e.Encode(xmlMapEntry{XMLName: xml.Name{Local: k}, Value: v})
}
return e.EncodeToken(start.End())
}
func main() {
type Family struct {
Siblings map[string]string
}
type MyFamily struct {
Siblings xmlMap `json:"siblings" xml:"siblings"`
}
// In reality, "f" comes from a function in an outside package...e.g. "f := somepackage.Function()"
f := &Family{
Siblings: map[string]string{"bob": "brother", "mary": "sister"},
}
var m = &MyFamily{}
*m = MyFamily(*f)
x, err := xml.Marshal(m)
if err != nil {
panic(err)
}
fmt.Println(string(x))
}
The Family struct comes from an outside package. I created MyFamily struct in order to add json and xml tags. If I try to xml encode MyFamily then I get an error:
xml: unsupported type: map[string]string
This is easily resolved by implementing the custom XML marshaller that I have done.
This creates a separate problem. I have tried to simplify the example but "f" comes from a function in an outside package...e.g. "f := somepackage.Function()". When I try to Alias f to m I get the error:
cannot convert *f (type Family) to type MyFamily
This happens because Family has a map[string]string but MyFamily has xmlMap. Even though they are the same underlying type I get that error.
The question is, how do I implement my custom struct tags AND be able to XML encode a map?
EDIT: This is a simple example and can just be resolved by
var m = &MyFamily{Siblings: f.Siblings}
Since there are MANY fields in both Family and MyFamily this is just inefficient and just wanted to know if there's a better way.