I'm confused about the behaviour of the following code. playground
var foo json.RawMessage
_ = json.Unmarshal([]byte(`{ "zoo": 123 }`), &foo)
enc := json.NewEncoder(os.Stdout)
// Works as expected
_ = enc.Encode(struct{ Foo *json.RawMessage }{&foo})
// MarshalJSON has a pointer reciever, so it doesn't get invoked here
_ = enc.Encode(struct{ Foo json.RawMessage }{foo})
// How is MarshalJSON being invoked if .Foo is not a pointer?
_ = enc.Encode(&struct{ Foo json.RawMessage }{foo})
Output:
{"Foo":{"zoo":123}}
{"Foo":"eyAiem9vIjogMTIzIH0="}
{"Foo":{"zoo":123}}
I don't understand why the third call to json.Encoder.Encode
is able to access json.RawMessage.MarshalJSON
even though it's not a pointer.