▲ | divan 4 days ago | |||||||
Some people in comments jump to the conclusion that Go allows conflicting names in embedded structs. It doesn't not – for the embedded structs of the same depth. These won't compile:
The case in article is about field names of the different depth. Spec is very clear about this behavior, and it was intentional.One of the reasons why handling same field names is different at different nesting levels is to protect against changes in structs coming from external libraries. Or, better phrased, external structs should not dictate what names you're allowed to use in your own structs (so they have priority). I.e. when you create a struct with another embedded struct (possibly from other package):
you don't want to depend on whether Bar already has URL. Your depth level has higher priority.Even more, imagine in the future authors of `somepackage` decided to add URL to their struct and it suddendly started to break your code from being compiled. I agree that behavior in the OP article example is confusing (and so is the code - do you want URL of Foo service or Bar service?). Yet, this behavior is intentional and documented. As usual, it's a subtle tradeoff here. If this feature would be implemented differently (say, compile time error for all depth levels), we would see an article with rant on how external structure changes breaks compilation. | ||||||||
▲ | ActionHank 4 days ago | parent | next [-] | |||||||
I don't really use golang all that much and even I was confused about OP's point because of the different depths. I feel like sometimes people just want to complain. | ||||||||
| ||||||||
▲ | NooneAtAll3 4 days ago | parent | prev [-] | |||||||
> Even more, imagine in the future authors of `somepackage` decided to add URL to their struct and it suddendly started to break your code from being compiled. doesn't this just shove the problem down a level? e.g. if somepackage.Bar suddenly gets a member with same name as one of your URL members? | ||||||||
|