Go embedded structs and pointer receivers

While working on a PR for the Azure storage GO library I discovered (yet another) corner of Go that confused the hell out of me. I know enough about embedded types/structs to use them effectively (so I thought) and I know the difference between receivers and pointer receivers. But when using them together you really need to make sure you’re careful.

The specifics of the problem I hit was that in the Azure GO library we have the struct called “Entity” which is used for table storage. Now, for purposes I wont go into I needed to create a another struct called BatchEntity which was declared as such:

type BatchEntity struct {
Entity
otherstuff string
}

Now, the Entity struct has a very useful JSON formatting method with the signature:

func (e *Entity) MarshalJSON() ([]byte, error)

Please please PLEASE note that this is a pointer receiver! Now I’d spend an embarrassingly long time trying to figure out why when I tried to marshal my BatchEntity class, why it didn’t call this MarshalJSON method as I expected. Of course it turned out that when I passed the marshalling method BatchEntity.Entity (referencing the embedded type) it would *somehow* (I haven’t figure out the specifics yet) treat it as a regular receiver and not call the MarshalJSON method since that specifically had a pointer receiver. I still need to dig into the details but this is a big warning to me, when dealing with embedded types make sure you check the receivers of the base structs. Would have saved me hours!!!

Kind of surprised there wasn’t a compile warning/error around that….   but I need to dig further.