猿问

指针接收器混淆

我对以下代码的行为感到困惑。操场


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即使它不是指针。


拉丁的传说
浏览 138回答 1
1回答
随时随地看视频慕课网APP

相关分类

Go
我要回答