I think the problem is that people try to use embedding in place of 
inheritance. You can see that in the original author's example involving 
Cat, Animal, and Pack. Embedding shares many similarities to inheritance, 
such as method promotion, but they are not the same. Embedding is in a way 
more restricted and less capable than inheritance in other languages, 
because embedding is just a plain syntax sugar. In the original author's 
example, calling *pack.MarshalJSON()* is actually calling 
*pack.Animal.MarshalJSON()*. When used in the context of inheritance, it 
becomes misleading because *pack.MarshalJSON()* implies marshalling the 
Pack when it is actually marshalling the Animal in the Pack.

On Tuesday, February 23, 2021 at 11:32:51 AM UTC+7 Ian Lance Taylor wrote:

> On Mon, Feb 22, 2021 at 12:52 PM mi...@ubo.ro <mi...@ubo.ro> wrote:
> >
> > Is there any proposal in Go 2.0 to remove the promotion of methods on 
> embedded struct fields or do you think it's a good idea ? For example in 
> the code below if someone marshals `Pack`, only `Animal` is actually 
> marshalled. Cat field is skipped. If he wants to marshal Cat as well the 
> developer must write an additional wrapper method(MarshalJSON) on `Pack` 
> and any other struct that embeds `Animal`. This becomes an even bigger 
> issue if you create types dynamically (using reflect). Actually I believe 
> reflect.StructOf is actually broken because of this feature (i.e. it panics 
> if the embedded type has methods).
> >
> >
> > type Pack struct{
> > Animal
> > Cat Cat
> > }
> >
> > func (a *Animal)MarshalJSON()([]byte, error){
> > // custom animal marshalling
> > }
>
> There are no plans to remove method promotion. It's true that method
> promotion can lead to surprising results. Programs should only use
> embedded fields when they can take full responsibility for all the
> consequences.
>
> Ian
>

-- 
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/67c88f67-34f3-4801-9e4c-e1e072803806n%40googlegroups.com.

Reply via email to