我對以下代碼的行爲感到困惑。 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})
輸出:
{"Foo":{"zoo":123}}
{"Foo":"eyAiem9vIjogMTIzIH0="}
{"Foo":{"zoo":123}}
我不明白爲什麼要json.Encoder.Encode
第三次調用能夠訪問json.RawMessage.MarshalJSON
即使它不是一個指針。
第三呼叫不調用MarshalJSON(),它使用反映猜測的類型和編碼爲最好是可能的。看看json。(* Encode).Encode()函數:http://golang.org/src/encoding/json/stream.go?s=4283:4330#L173 – divan
@divan怎麼沒有在第二個例子中發生? –