On Sat Sep 14, 2019 at 1:43 AM Sathish VJ wrote:
> I saw some code where there is a temporary type called *noMethod* created 
> before performing custom marshaling.
> What is the purpose of doing this?
> type T struct {
>  A int
>  C string
> }
> func (t T) MarshalJSON() (text []byte, err error) {
>  type noMethod T
>  return json.Marshal(noMethod(t))
> }
> https://play.golang.org/p/e8cZfkU1uvE 

When json.Marshal is called, if the value passed implements
json.Marshaler, then that method is called to marshal the value.

If you wrote

    func (t T) MarshalJSON() (text []byte, err error) {
        return json.Marshal(t)

    func main() {
        var t T

then you'd end up with infinite recursion, as the T.MarshalJSON() method
would just keep getting called. By defining `type noMethod T` and
casting t to a noMethod before calling json.Marshal, you can avoid this
because the noMethod type has, well, no methods, and thus does not
implement json.Marshaler and will be encoded using the struct encoder.

In this case, you may as well just not implement json.Marshaler at all
and fall through immediately to the struct encoder, but perhaps there's
some reason to do this that your example doesn't show.

You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 

Reply via email to