Ambiguous Method Promotion Bug?

65 views
Skip to first unread message

Michal Ostrowski

unread,
Nov 17, 2020, 3:57:06 PM11/17/20
to golang-nuts

Here is a playground doc that demonstrates what seems to be strange behavior regarding promotion of methods.

https://play.golang.org/p/R9M1lAOd9CA

It seems that I can generate a struct a have an ambiguous method by adding a level of indirection in struct definitions.  Or there's something in the language spec that I'm missing (and I'd appreciate a reference to that in that case.)



Axel Wagner

unread,
Nov 17, 2020, 4:15:45 PM11/17/20
to Michal Ostrowski, golang-nuts
Hi,

the relevant spec section is https://golang.org/ref/spec#Selectors

A selector f may denote a field or method f of a type T, or it may refer to a field or method f of a nested embedded field of T. The number of embedded fields traversed to reach f is called its depth in T. The depth of a field or method f declared in T is zero. The depth of a field or method f declared in an embedded field A in T is the depth of f in A plus one.

and

For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. If there is not exactly one f with shallowest depth, the selector expression is illegal.

In your example, zz.Fun refers to zz.Y.Fun, as that has a depth of 1, whereas zz.Q.Fun has a depth of 2 (Q has depth 1 and Fun has depth 1 within Q) and zz.X.Fun (X has depth 2 in Z and Fun has depth 0 in X).

Note, in particular, that the check happens at the selector expression, not at the type-definition. This is intentional, as it means you can embed multiple types without it being an error if they have the same fields/methods.

I agree that all of this makes not necessarily for the most readable code, but the rule that the shallowest depth must be unique is what makes the selector well-defined.

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/cb606644-1b76-4db1-af8c-96b5efac1c20n%40googlegroups.com.

Axel Wagner

unread,
Nov 17, 2020, 4:16:30 PM11/17/20
to Michal Ostrowski, golang-nuts
"and so does zz.X.Fun", of course.
Reply all
Reply to author
Forward
0 new messages