I'm working with some "generic" functions in Go that operate on interface{}
and send things around channels, etc. Slimmed down, let's say I have something like:
type MyType struct {
// Fields
}
func (m *MyType) MarshalJSON() ([]byte, error) {
// MarshalJSON
log.Print("custom JSON marshal")
return []byte("hello"), nil
}
func GenericFunc(v interface{}) {
// Do things...
log.Print(reflect.TypeOf(v))
log.Print(reflect.TypeOf(&v))
b, _ = json.Marshal(&v)
fmt.Println(string(b))
}
func main() {
m := MyType{}
GenericFunc(m)
}
This outputs:
2014/11/16 12:41:44 MyType
2014/11/16 12:41:44 *interface {}
Followed by the default json.Marshal
output, rather than the custom one. As far as I can tell, that's because the call to Marshal
sees a value of type pointer-to-interface rather than pointer-to-MyType.
Why do I lose type information when I take &v
? I would expect the second line of the output to be *MyType
and not *interface {}
.
Is there any way for me have the custom JSON Marshaller called without explicitly casting?