When you create a struct with another embedded struct (possibly from other package):
type Foo struct {
somepackage.Bar
URL string
}
you don't want to depend on whether Bar already have 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.
Example in the OP article is a corner case where this behavior is creating ambiguity, indeed. Yet, it's documented and intentional.
If you need to grab a particular struct's version of the data, you can via `opts.BarService.URL` or `opts.FooService.URL`: https://go.dev/play/p/MUSYJhmoC2D
Still worth being careful, but it can be useful when you have a set of common fields that everything of a certain group will have (such as a response object with basic status, debug info, etc. and then additional data based on the particular struct). I don't know why they let you embed multiple layers and multiple objects though. I've never gotten value out of anything but a "here's a single set of common fields struct embedding".
So I got curious and I looked at the compiler source code, and it does a depth-first search.
The fascinating bit to me is that there is a consolidateMultiples function in go/src/go/types/lookup.go (lines 286-304) that detects when multiple embedded types at the same depth provide the same field name. I wonder why they don’t do this for all levels. How deep could this even be in practice for it to matter? You could just have a hashmap with them all.
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).
Over the course of ~10 years of writing Go, my ratio of "embedding a struct" to "regretting embedding a struct" is nearly 1:1.
I do not embed structs anymore. It is almost always a mistake. I would confidently place it in the "you should be required to import 'unsafe' to use this feature" bin.
I think embedding structs would be way more useful if a) there would be properties on interfaces and b) there would be generic methods available.
As long as these two aren't there, embedding structs is literally identical to dispatching methods, and can't be used for anything else due to lack of state management through it. You have to manage the states externally anyways from a memory ownership perspective.
My personal conspiracy is that Golang is an epic prank.
Make a language that's really good in some ways and just horrible in other ways for no reason whatsoever.
So that when it's critics point out contradictory features like embedding, it's defenders can be the ultimate troll and say things like "but, actually, it's a simple language because it doesn't have while loops".
It's the best explanation I have for some of the cognitive dissonance surrounding the language design.
Would you care to make a list of all the problems your favorite language has served up to you at a rate of once in ten years, so I can also write a post making your language sound horrible as a result?
It's my common code review comment to the beginners to not embed structs. There's rarely anything to be gained by doing so. The only use case I found to be useful is to embed something like:
where I get to override only a part of a bigger interface at a time and have the embedding take care of the rest by saying panic("unimplemented") to satisfy the interface.
Maybe I see it differently, but it made sense: embeding works only at 0 depth, it's like a macro to access rapidly the fields of the embedded struct, it doesn't go beyond that,there is no inheritance.
When embedding BarService, the field being embedded is BarConnectionOptions
Spec: https://go.dev/ref/spec#Selectors
> x.f resolves to the field/method at the shallowest depth in T. If there isn’t exactly one at that depth, it’s illegal.
Embedding promotes fields; on name collisions the shallowest wins. So `opts.URL` is `FooService.URL` (depth 1), not `BarConnectionOptions.URL` (depth 2).
That something is clearly specced doesn’t imply all developers actively know it.
Even given that it compiles, I wouldn’t exclude it being a runtime error.
But the big problem isn’t that it behaves as advertised, it’s that it is way too easy to write opts.URL where you mean opts.Bar.URL. Auto-complete will happily compete the wrong thing for you.
I have code that wouldn't work without embedding. Basically, I have a type that annotates any AWS paginate and is capable of streaming all the results as a sequence. It embeds the original client so you get all the functionality of the client, but it also wraps the functions that support a pagination. I can't think of an easier or clearer way to do it.
Making the compiler fail that would indeed be nice. A clear example of a language feature that makes sense when there's a single developer, but in a code base with hundreds of developers, this could easily break something without anyone noticing.
This is a "you had one job" level language defect. If there are excuses that allow Go to pretend that structs with duplicate member names are well formed, good programming language designers would reject them in horror and specify how the compiler should actively look for this type of mistake, without wasting effort to look for such excuses.
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:
type Bad struct {
Name string
Name string
}
type A struct{ Name string }
type B struct{ Name string }
type C struct {
A
B
}
bad.Name() // compile error: other declaration of Name
c.Name() // compile error: ambiguous selector c.Name
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):
type Foo struct {
somepackage.Bar
URL string
}
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.
Why would you ever do opts.URL instead of opts.FooService.URL or opts.BarService.URL? What does ambiguity and imprecision gain you here when you can just write out from which struct you want it from? I don't even know why opts.URL would compile, it's completely unstated that you're not grabbing it from opts but grabbing it from some other structure contained within opts. Shouldn't even compile IMO, but at least I found something I disagree with Go's designers on.
27 comments
[ 3.4 ms ] story [ 51.8 ms ] threadEven 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.
Example in the OP article is a corner case where this behavior is creating ambiguity, indeed. Yet, it's documented and intentional.
Still worth being careful, but it can be useful when you have a set of common fields that everything of a certain group will have (such as a response object with basic status, debug info, etc. and then additional data based on the particular struct). I don't know why they let you embed multiple layers and multiple objects though. I've never gotten value out of anything but a "here's a single set of common fields struct embedding".
The fascinating bit to me is that there is a consolidateMultiples function in go/src/go/types/lookup.go (lines 286-304) that detects when multiple embedded types at the same depth provide the same field name. I wonder why they don’t do this for all levels. How deep could this even be in practice for it to matter? You could just have a hashmap with them all.
I hope the feature mentioned in the article will cause a compiler error.
However, I wouldn't use this approach when writing my own code.
It's a one of a few rough edges in Go.
I do not embed structs anymore. It is almost always a mistake. I would confidently place it in the "you should be required to import 'unsafe' to use this feature" bin.
As long as these two aren't there, embedding structs is literally identical to dispatching methods, and can't be used for anything else due to lack of state management through it. You have to manage the states externally anyways from a memory ownership perspective.
Make a language that's really good in some ways and just horrible in other ways for no reason whatsoever.
So that when it's critics point out contradictory features like embedding, it's defenders can be the ultimate troll and say things like "but, actually, it's a simple language because it doesn't have while loops".
It's the best explanation I have for some of the cognitive dissonance surrounding the language design.
This problem has happened to me once.
Would you care to make a list of all the problems your favorite language has served up to you at a rate of once in ten years, so I can also write a post making your language sound horrible as a result?
When embedding BarService, the field being embedded is BarConnectionOptions
Spec: https://go.dev/ref/spec#Selectors > x.f resolves to the field/method at the shallowest depth in T. If there isn’t exactly one at that depth, it’s illegal.
Embedding promotes fields; on name collisions the shallowest wins. So `opts.URL` is `FooService.URL` (depth 1), not `BarConnectionOptions.URL` (depth 2).
Even given that it compiles, I wouldn’t exclude it being a runtime error.
But the big problem isn’t that it behaves as advertised, it’s that it is way too easy to write opts.URL where you mean opts.Bar.URL. Auto-complete will happily compete the wrong thing for you.
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.