【发布时间】:2015-08-28 18:07:46
【问题描述】:
我对以下代码的行为感到困惑。 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() 函数:golang.org/src/encoding/json/stream.go?s=4283:4330#L173
-
@divan 为什么在第二个例子中没有发生这种情况?
标签: go