Yes, that makes sense.  Thank you.

The example I wrote was concocted.  But I've seen others do it on their own 
types too, which didn't make sense at all.  Maybe they were just 
copy-pasting similar code from elsewhere.

On Saturday, 14 September 2019 20:20:49 UTC+5:30, Ben Burwell wrote:
>
> 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 
>         json.Marshal(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 
https://groups.google.com/d/msgid/golang-nuts/aeea2f49-58e1-42d8-806a-56cdf899c70c%40googlegroups.com.

Reply via email to