New methods on imported structs: how do I do this with complex external structs

133 views
Skip to first unread message

Glen Newton

unread,
Oct 13, 2020, 4:26:51 PM10/13/20
to golang-nuts

Hello,

Context: looked at:
as well as the discussion on this issue:
""cannot define new methods on non-local type ___" is not always an error #31631"

Often, the imported structs are inter-related, and you might be wanting to add a method to a struct that is contained in another external struct directly or as an array. So the solution suggested both in the stackoverflow response, and in the github discussion appear to me (please correct me if I am mistaken) not help with more complex external struct inter-relationships.

Please take a look at my example in the playground:

I would like to add a method to an external struct, then add an array of these to a struct that contains an array of the original external struct. Using either a new type or embedding a type will not work, creating either a:
> cannot use make([]bEmbedded, 10) (type []bEmbedded) as type []B in assignment
or
> cannot use make([]bType, 10) (type []bType) as type []B in assignment

Am I going about this the wrong way?  :-)  I would appreciate help on this.

[Apologies if this has already been asked and resolved]

Thanks,
Glen

Volker Dobler

unread,
Oct 14, 2020, 1:54:56 AM10/14/20
to golang-nuts
You cannot do this.
1. You cannot add methods to imported types.
2. Embedding is not inheritance. (While sometimes things which
are often done via inheritance can be done with embedding too
embedding simply is not inheritance and leads to a totally different
type.)  
3. Go's slices (and arrays) are not covariant.
What you try to do is simply impossible. You must redesign. 

V.

Reply all
Reply to author
Forward
0 new messages