-
Notifications
You must be signed in to change notification settings - Fork 18k
encoding/json: Marshal skips checking Marshaler implementation for nil pointer #48430
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This is working as documented:
For better or worse, we can't change that right now, as it would break existing users of the API. |
Closing as the current behavior seems well-documented and can't be changed with breaking existing usages. |
Feels like the documentation is just pointing to a bug that exists. The thing that scares me is Go being ended up like Javascript that can’t fix so many bugs because existing codes rely on them. The example I wrote in the playground is what I expect to happen. I want control over the process of marshaling, even if it’s a nil pointer. Sadly it’s not possible and I have to write a messy code to gain that control. I just hope it can be fixed in Go2 |
I'm not sure I agree that calling 'MarshalJSON' on a nil pointer is behavior that people expect. I actually believe the current behavior is correct. |
It’s arguable. The interface is not exactly a nil without any identity. It has a type if you use reflect on it. And olso if you check it, it satidfies the json.Marshaller interface. It’s very different from a simple nil. We implement the json.Marshaller for a reason. To have control over the flow. It’s a little odd that we expect our reciever not to be called in some situations. This tells us we don’t have the full control over the code. |
My earlier comment was serving as a counter-argument to the claim that the current behavior is a bug that must be fixed. Both behaviors are reasonable. In the absent of an obviously right approach, we need to pick one and document it. That's what the current Also, if you want a want to ensure the json.Marshal(struct{ *aStruct }{theStruct}) |
Go version:
Does this issue reproduce with the latest release?
yes
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
I tried to call
json.Marshal
func on theencoding/json
package and give it a nil pointer of my custom-defined type that satisfies thejson.Marshaler
interface.I tried to write the simplest example. Please look at the output for the
b1
andb2
variables in the playground .What did you expect to see?
I expected
json.Marshal
called theMarshalJSON
receiver that is defined on my custom-defined type since it already implementsjson.Marshaler
.What did you see instead?
If the passed interface argument is a
nil pointer
, thejson.Marshal
method doesn't check if it satisfies thejson.Marshaler
or notThe text was updated successfully, but these errors were encountered: