Skip to content
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

encoding/json: using MarshalJSON declared on pointer receiver with non-pointer values #6468

Closed
gopherbot opened this issue Sep 24, 2013 · 2 comments

Comments

Projects
None yet
2 participants
@gopherbot
Copy link

commented Sep 24, 2013

by Lytvynov.A.V:

What steps will reproduce the problem?
If possible, include a link to a program on play.golang.org.
http://play.golang.org/p/ZAsj63RNx0

What is the expected output?
{"S":"IkhlbGxvIg=="}
{"S":"IkhlbGxvIg=="}

What do you see instead?
{"S":"Hello"}
{"S":"IkhlbGxvIg=="}

Which compiler are you using (5g, 6g, 8g, gccgo)?
6g

Which operating system are you using?
Debian Wheezy

Which version are you using?  (run 'go version')
go version devel +1607e9e9e6de Tue Sep 24 00:17:08 2013 -0400 linux/amd64
(also works on the playground)

Please provide any additional information below.
Field S in the struct is of type Str and does not have MarshalJSON in it's method set.
This means that S is not json.Marshaler.
But because reflect.Value.CanAddr for this field in the first case returns true,
json.Marshal will use address of that field to try to assert it to json.Marshaler.
@rsc

This comment has been minimized.

Copy link
Contributor

commented Sep 24, 2013

Comment 1:

If you pass a var x *Foo to json.Marshal, marshal can use &x.Str to get at
its methods. But if you pass a value x, which cannot have its address
taken, then the rewrite is not possible and json.Marshal cannot invoke the
MarshalJSON method. I have tested that after Brad's recent fix your
playground snippet behaves the same way at tip as it did in Go 1.1.
The behavior in JSON matches what Go does:
func Ptr() *Foo
func Value() Foo
func _() {
    Ptr().Str.MarshalJSON()
    Value().Str.MarshalJSON()
}
illustrates the difference.

Status changed to WorkingAsIntended.

@gopherbot

This comment has been minimized.

Copy link
Author

commented Sep 24, 2013

Comment 2 by Lytvynov.A.V:

Thanks for your response.
Yes, I understand why and how this works.
I was wondering if it *should* do it this way.
But I won't argue, if you think it's ok.

@golang golang locked and limited conversation to collaborators Jun 25, 2016

This issue was closed.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
You can’t perform that action at this time.