-
Notifications
You must be signed in to change notification settings - Fork 17.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: spec: remove embedded struct #22013
Comments
(I assume you mean removing embedded types in general, rather than just embedded structs, which are simply a common type to embed.) Without casting any judgement on this proposal, I note that embedding is also a significant cause of complexity in the language and implementation. |
I agree with your presentation of the limitations but disagree with your conclusion to remove it from the language. Embeddings are useful (and the limitations negligible) when you have lots of little types 'embedding' off another little one. It is far less cognitive load to think of Looking at your alternative, which you wrote as:
Imagine the realistic case where Lastly, how often have we seen embedding used horrifically? I've seldom seen it (feel free to prove me wrong with links to stuff I'll need to follow up with eye-bleach), and I say if it aint broke dont fix it (especially considering it represents an additional break from Go1 compatibility). |
Yes, it does not solve inheritance problems, because embedding is not intended to solve inheritance problems. Because it does not solve what it was not intended to solve, the above rationale about why to remove it makes no sense to me. |
I agree with neither the technical accuracy of the premise nor the final conclusion. Inheritance locks in functional dependencies in the base class. Embedding allows those dependencies to be overridden or propagated at a per-method granularity. |
I frequently use interface embedding when only a few interface methods must be overridden: // StatsConn is a `net.Conn` that counts the number of bytes read
// from the underlying connection.
type StatsConn struct {
net.Conn
BytesRead uint64
}
func (sc *StatsConn) Read(p []byte) (int, error) {
n, err := sc.Conn.Read(p)
sc.BytesRead += uint64(n)
return n, err
} or // AuthListener is a `net.Listener` that rejects unauthorized connections
type AuthListener struct {
net.Listener
}
func (al *AuthListener) Accept() (net.Conn, error) {
for {
c, err := al.Listener.Accept()
if err != nil {
return c, err
}
if authorizeConn(c) {
return c, nil
}
c.Close()
}
} There is no need in implementing other |
@griesemer Yes. Embedded types is the more accurate term. I used embedded struct in the example because it is more evil compared to embedded interface. I would think that it shouldn't be that difficult to type out the full interface signature than relying on interface embedding. @twitchyliquid64 Sorry if I didn't give a clear example earlier. What I meant to say was instead of doing the following:
You have two alternatives. First, you can use the real composition and employ method forwarding, which would be as follows:
It is true that it takes a little duplication (which requires little to no additional effort), but the given the benefit of having the TruckDriver decoupled from the BaseDriver and easier maintenance in the future, I say it's worth it. Alternatively, you may refactor the common method into function. So the above code snippet will now look like this:
The benefit of this approach is that each driver exists independently, and the Drive functionality is decoupled from any specific driver. You can change one or the other without worrying about unforeseen domino effect. I prefer having my types flat rather than deep. The problem with type hierarchy is that it is difficult to tell what other things you may break when you make a slight alteration to your code. Given that embedded types is a major feature in Go, I am actually surprised to see that it isn't used as much as I anticipate it to be. It may be due to its certain characteristics, or simply people having no particular need for it. At least, gophers don't go crazy with constructing the different families of apes (or may be not yet). Regardless, I don't agree with the "if it ain't broke, then don't fix it". I am more of a "broken windows theory" guy. Go 2.x is the opportunity to take lessons learned from Go 1.x and makes the necessary improvements. I would think that the resulting simplicity from the removal of unnecessary features may bring about other future opportunities (eg. other potentially good ideas that may be difficult to implement due to the complexity of the current implementation). @cznic It behaves exactly like inheritance. Changes to the base type is automatically inherited by the derived types. If it does not solve the problems that inheritance is meant to solve, then I don't know what does. @as I have no idea what you are talking about. Here is an illustration. The last I checked my Parents were normal human beings. Since I am meant to function as a normal human being, I inherit from them so that I too can be a human. However, one day, my Parents abruptly decide to grow scales and a pair of wings, and breath fire. Since I inherit from them, I am too automatically turned into a dragon (without my permission!). Since I am expected to function as a human, it breaks my intended functionality. I could insist in being human by overriding the inherited behavior from them. However, no one can tell what other crazy things they may do in the future that will again break my functionalities. That is doable in both inheritance and in Go's embedded types. |
It does not behaves like inheritance at all. Given type T int
func (T) foo()
type U struct {
T
}
var u U
|
@cznic I agree with you that T is embedded in U and that is composition. However, the real issue is with the automatic propagation of T characteristics (even if those characteristics are still technically belong to T). Now, in order to learn what I can do with U (as a consumer of U), I have to learn what T does as well. If T changes, I as the consumer of U, have to be aware of those changes as well. This is the inheritance-like behavior I was talking about. It is simple if it involves only T and U. Imagine if T embeds X, and X embeds Y, and Y embeds Z. All of a sudden, you get the monkey and the banana problem. |
In order for any proposal along these lines to be adopted, you'll need to do some analysis of where and how current Go programs use embedding, and how difficult it would be for them to adapt. You could start with just the standard library. |
No, it enhances your functionality. If your intended behavior is to be Human, there is nothing the embedded type can do to change that or take it away. Sure, for some reason if the original type gained a method
You could say you're say you're a dragon, but you're not. You're a fire breathing human who appreciates complex numbers. Your concerns seem to be about the general concept of functional dependency than about the inheritance problem. These exists in packages, interfaces, function parameter lists, and the list goes on. |
That claim is not obvious to me. Could you give some concrete examples? |
@ianlancetaylor I'll see what I can do. @as It's actually pretty cool to be a fire-breathing human once in a while. But how much I will stay as a human depends on my earlier expectation of my Parents. If I thought that my Parents were already humans and therefore I didn't implement much humanity in me (because it was already implemented by my Parents), when my Parents turn into a giant lizard, I too will turn. Basically, I don't become what I expect myself to be, but I am actually the enhanced version of my Parents (whatever my Parents want to be). You may argue that this is technically the correct definition of inheritance (and it is), but it breaks the original assumption about me. The assumption about me depends on my assumption about my Parents, whereas my Parents don't necessarily know (and don't need to!) my assumption about them. The main issue is that I don't encapsulate my Parents trait in me. When my client deals with me, they also have to deal with my Parents, and possibly my Grandparents as well. It creates unnecessary coupling and breaks encapsulation. Changes in one will have a domino effect on the others. With proper encapsulation, the effect of a change should be contained like ship compartmentation. Again, it depends on whether this is the intended behavior that the Go's Team wants in Go language. If it is then I say they should not hesitate and support the proper inheritance all the way. After all, despite its criticism, inheritance is still a major feature in many popular programming languages today. If they do not want it, then they should scrap it and I vote for scrapping it. |
That is only true at small scales: at larger scales, the advantage of embedding is that you do not need to update forwarding for each newly-added method. If you embed a |
@bcmills The problem with automatic method implementation is that the people who write |
@henryas I don't personally find that to be a particularly convincing argument. The fact that it is possible for a program to misuse some feature of the language does not imply that that language feature should be removed. You need to a longer argument; for example, you might argue that the misuse is a common error that people routinely make. |
@ianlancetaylor if you read my earlier posts, I did point out that ... well, I will summarize it again here:
By the way, those are common arguments against inheritance and none of them is my invention. So I really don't need to prove their validity and how they apply in practice. They have been around for years, expounded by experts and practitioners alike. They are relevant to Go's embedded type because despite it not being technically an inheritance, it exhibits an inheritance-like behavior that causes it to share the same pros and cons of an inheritance. As mentioned before, despite arguments against inheritance, inheritance is still widely used in many programming languages today. So it's really up to the Go's Team to decide which direction they want to take Go language to. In my opinion, embedded type is not a needed feature and can be removed from the language. However, should the Go team decide to keep this feature, I would say there is no need to complicate it by making it look like an inheritance in disguise. After all, you are still getting all the side effects of a proper inheritance anyway. Just take the common road to inheritance, and boldly claim this is inheritance. It is simpler that way and you most likely have all the kinks already ironed out by other languages who share the same road. |
@henryas Thanks, but I'm not asking for a list of possible errors. I'm asking for an argument that these are errors that people commonly make. To put it another way, every reasonably powerful language has features that can be misused. But those features also have a benefit. The question, as with all language questions, is how to weigh the benefits against the drawbacks. The fact that a feature can be misused is a minor drawback. The fact that a feature frequently is misused is a major drawback. You've demonstrated a minor drawback. I'm asking whether you can demonstrate a major one. We don't call embedded types inheritance because it is not inheritance as most people use the term in languages like C++ and Java. For us to call it inheritance would be confusing. See also https://golang.org/doc/faq#Is_Go_an_object-oriented_language and https://golang.org/doc/faq#inheritance . |
@ianlancetaylor What you are asking is difficult to quantify. How do you weigh one feature against another? How do you measure the benefits and the drawbacks, and whether they are major or minor? It isn't as simple as counting loc. The best that I can think of is by drawing opinions from everyone's experience with real-life projects whether they would rather have the feature or its absence. In the Go projects that I have been involved with so far, there have been very little use of embedded types. If I recall correctly, we might have used embedded types for some small, simple types. We can live without the feature with no problem. It shouldn't take much effort to refactor the code. In fact, thinking back, it may be better to not use embedded types. However, considering the types involved are minor, small, and very unlikely to change, I would say, in our projects so far, it makes little difference between using the embedded types and not. Our team is also small. The longest distance between one person to another is just one table away. So the ease of communication may help in a way. In addition, the base and the derived types were usually written by the same person. So I would say it is quite difficult to judge the merits (or their absence) of embedded types from my own projects. However, I would think that embedded types is a superfluous feature. About why I mention inheritance when the subject is about embedded types, I briefly mentioned this in the earlier post:
I will elaborate further, and attempt to compare Go's embedded types to the common notions of inheritance and composition. I will use Parent and Child rather than Base and Derived. InheritanceWhat is inheritance? Inheritance is described as an "is-a" relationship between two types. The Parent defines the identity, and the Child is essentially the Parent with additional features. You can think of the Child as the enhanced version of the Parent. If the Parent is a fish, then the Child is a super fish. If the Parent is a bird, then the Child is a super bird. How is this relationship implemented in practice? It is implemented by having the Parent's characteristics automatically exposed by the Child. Now let's compare this to Go's embedded types.
Now, what if we changed the Parent to be a bird.
As seen from the above illustration, Go's embedded types behaves like inheritance. The Parent defines the identity, and the Child is the Parent with some enhancements. Another aspect of inheritance is the Child's ability to override the Parent's behavior to provide more specialized behavior. We'll see how we can do that with Go's embedded type.
Again, we see inheritance-like behavior in Go's embedded type. Now, how do you implement inheritance? Different languages may have different implementations, but I would think that the Child would need to hold some kind of reference to the Parent in order for it to work. If you describe it in Go, it would look something like this:
Voila! It is embedded type! Is Go's embedded type actually an inheritance? You decide. However, there is an important difference between Go's embedded type and the normal inheritance. The normal inheritance exposes only the Parent's behavior. On the other hand, Go's exposes both the Parent's behavior and the Parent itself. The question to ask is whether there is any benefit to doing so? CompositionNow, we will compare Go's embedded type to composition. Composition is defined as a "has-a" relationship between two types. A Person has a Pencil, but the Person is definitely not a Pencil. The Child controls its own identity and the Parent has no control whatsoever over the Child. In Go, proper composition should look like this:
The important thing to note here is that Pencil is well encapsulated by Person. The definition of Pencil does not automatically apply to Person. If you try to use embedded type to describe this "has a" relationship:
that very definition of "has a" (composition) will break, as embedded type resembles more of an "is a" (inheritance) relationship than a "has a" relationship. ConclusionLet's start by calling a spade a spade. Go's embedded type is inheritance. It describes an "is a" rather than a "has a" relationship. Technically, it is inheritance disguised as composition. The thing is why do it in a queer roundabout way if what you need is plain inheritance. Is there any benefit to doing so? I think Go 2.x is a great opportunity to fix it or ditch it. |
It is not.
Go does not have inheritance, so embedding is not a round about way of providing inheritance as Go does not provide that feature. In Go value types satisfy the "is-a" relationship, and interface types satisfy the "has-a" relationship. |
@davecheney Is the last sentence saying what you want to wrote? It seems to me it's the other way around. Or I'm really confused before the first coffee of the day. |
@davecheney I am puzzled.
If Go value types satisfy the "is-a" relationship, how do you describe "A Carpenter is a Person that build furniture. A Singer is a Person that sings" in Go value types?
The above code has no interface whatsoever, and yet the Person "has a" Pencil. Where does that leave embedded types? What is the relationship between the embedded and the embeddee? |
@cznic yup, that's about as clear as I can make it
A A |
There is no relationship. |
This is not correct, |
Go supports this already, at the risk of sounding sarcastic, these are just |
I would like to add that another problem with embedded type is the automatic exported field visibility. When you embed type A into type B, type A is directly accessible from type B. It is like two features (Visibility and Embedded Properties) rolled into one. In my opinion, it is better to have the visibility part separated from the embedded part. It is more orthogonal that way. Just imagine if changing your monitor's brightness also changes your speaker's volume. Unless that is exactly what you want, it is just awkward. Should you decide to keep embedded types in Go2, my proposed syntax for unexported embedded type is as follow: type A struct{}
func (A) DoSomething(){}
type B struct{
_A //unexported embedded type A
}
var b B
b.DoSomething() //Okay!
b._A = A{} //ILLEGAL: cannot access b._A My stance is still to consider removing embedded type from Go2. It makes Go2 a lot simpler and it compensates the additional complexity due to extra features that have accumulated since Go1.0. |
You chose wrong parents. Isn't it cool that you can choose the parents. :-) Joke aside, they are more like step-parents, they must keep the contract. Your fear is, what if they may break the contract. If that's troubling you, Go talk to them. |
I really like this idea. The class Greeter < ActiveRecord::Base
def hello
'hello'
end
end
class Foo < ActiveRecord::Base
belongs_to :greeter
delegate :hello, to: :greeter
end
Foo.new.hello # => "hello" Manually forwarding methods to a struct field is unnecessarily verbose and also introduces a problem with test coverage. |
I was going to disagree the existence with embedded struct BUT I realized it's useful if you are designing APIs. It will be lot easier to make Endpoint APIs from different perspectives with the same Resource since you can just extend it with extra information for frontend needs. // The resource that stores in the database.
type User struct {
ID int
Username string
}
// ...
type GetUserResponse struct {
User
// Extra information for this API only.
IsBlocked bool
}
// ...
type GetRelationshipResponse struct {
User
// Extra information for this API only.
FriendedAt time.Time
MutualFriends int
} Without embedded structs, you gonna either having a duplicated structs: // ...
type GetUserResponse struct {
ID int
Username string
IsBlocked bool
}
// ...
type GetRelationshipResponse struct {
ID int
Username string
FriendedAt time.Time
MutualFriends int
} Or include // ...
type GetUserResponse struct {
User User
IsBlocked bool
}
// ...
type GetRelationshipResponse struct {
User User
FriendedAt time.Time
MutualFriends int
} |
@henryas If you embed an exported type into a struct, you indeed leak information about the composition of the embedding type. However, one extra line gets you out of all the difficulties you mentioned regarding the lack of information hiding. You can indeed define a local, unexported type alias of the type you wish to embed, and embed that type alias instead: type Foo struct{}
func (Foo) DoSomething(){}
type foo = Foo // <--------------
type Bar struct {
foo
}
var bar Bar
bar.DoSomething() // Okay!
bar.foo = Foo{} // ILLEGAL: anonymous field foo is inaccessible outside Bar's package This is essentially the same idea as that proposed by @cznic in his comment, but it uses a type alias rather than a defined struct type. |
This proposal has been derailed into syntax hack and workaround. The problem is not the syntax, but the very idea of embedding itself. Concept-wise, when one embed A into B, what is the relationship between A and B? Is it an “is-a” where B is an A? Is it a “has-a” where B is composed of A? If it is an “is-a” where B is an A (eg. Alice is a Person), embedding does not work quite as well as a proper inheritance in other languages. The forwarded methods from A still refer to A instead of B. Quite a number of people in Golang-Nuts try to use embedding to simulate this relationship and got confused when things do not work as expected. For instance, there is one that tries to embed Animal into Cat. Animal has a Serialize method and the method gets promoted into Cat. So you can call Cat.Serialize(). However, when you call Cat.Serialize(), you are essentially calling Cat.Animal.Serialize() because it serializes the Animal and not the Cat. So the question is why do you need to promote the Serialize method into Cat in the first place since it has nothing to do with the Cat? In this respect, embedding cannot be used to sufficiently describe the “is-a” relationship. If it is a “has-a” relationship (eg. Alice has Eyes), embedding becomes awkward because of method promotion. One can already describe such relationship without embedding. You can call Alice.Eyes.Color without needing embedding. With method promotion it becomes awkward because Alice.Color does not refer to Alice’s color but it refers to her eyes’ color. In addition, the field and method promotion aspect of embedding results in increased coupling. The author of A may add fields and methods which may be relevant to A but no longer relevant to B. Inheritance is often viewed in a bad light because of a similar situation. When you have a long hierarchy of types, all it takes is just one bad API change that gets propagated down the lines and break the whole types in the group. At least in the case of Inheritance, Inheritance sufficiently explains the “is-a” relationship while it is not clear what kind of relationship Embedding is describing. People nowadays shun a long-hierarchy of interdependent types. Rust does not have inheritance to discourage this practice. Go’s embedding does nothing to discourage this. You may not like the term inheritance and you may say Go has composition and not inheritance, but Go’s embedding has all the inheritance bad charactertistics and none of its good ones. To me, embedding seems more like a convenient tool to copy-and-paste fields and methods of A into B, but then it may be clearer to have B.A.Characteristics() without embedding at all. Embedding is like one weird vocabulary that you do not know where to use. With IDEs, text-editors, code generators, etc., saving a few keystrokes seems like a bad excuse. In addition, without embedding, the compiler and other go tools may have easier and simpler ways to do their jobs. There is no magic between structs. At the same time, I recognize that Go 2 may require backward compatibility with Go 1 and there are people who use embedding all over the place. So it may not be practical to remove embedding, unless if Go has ways to deprecate features. This is why I do not pursue this proposal with such passion anymore, but I thought that this could be a good food for thoughts. |
@henryas As others before me have pointed out, you're mistaken about inheritance vs. composition. Go does not have inheritance, period. Via named struct fields, you get basic composition. Embedding simply adds automatic method and field promotion to the outer type. Are you implying that we should get rid of embedding simply because it's not the right approach in all cases? If so, your argument makes no logical sense to me. Of course, there are cases where embedding is not what you want. If you do not want automatic method and field promotion to the outer type, do not use embedding; simply use composition via a named struct field, and selectively delegate some of the methods if needed. However, there are plenty of cases where embedding is convenient and reduces boilerplate. See the source code of the
That is a valid point, and I agree that people shouldn't use embedding willy-nilly. For instance, I don't think embedding a third-party type is necessarily a good idea. Like all features of a language (reflection?), embedding can be abused—I'm actually drafting a blogpost on the topic. However, you shouldn't throw the baby out with the bathwater.
But wouldn't this approach result in the same kind of coupling that you were decrying above? Clients of the
I respect your point of view, but you can't speak for the entire community. |
I don't agree with removing embedding, but I do think that the discussion it created has made me believe that we should focus on re-thinking how we view embedding and teaching new patterns around it. A lot of the discussion here has focused on the "is-a" versus "has-a", which corresponds to inheritance versus composition. I think the problem is trying to make embedding fit strictly into the inheritance or composition boxes, when it is actually something different than both, and should be taught as such:
package main
type BatteryPowered interface {
Charge(int)
Deplete(int)
GetCharge() int
}
type Named interface {
GetName() string
}
type Device interface {
Named
BatteryPowered
}
type Battery struct {
charge int
}
func (b *Battery) Charge(amount int) {
b.charge += amount
}
func (b *Battery) Deplete(amount int) {
b.charge -= amount
}
func (b *Battery) GetCharge() int {
return b.charge
}
type Meta struct {
name string
}
func (m *Meta) SetName(name string) {
m.name = name
}
func (m *Meta) GetName() string {
return m.name
}
type Car struct {
Meta
Battery
}
type Phone struct {
Meta
Battery
}
func UseDevice(device Device) {
println("using " + device.GetName())
device.Deplete(24)
}
func main() {
car := Car{}
car.SetName("Mercedes")
phone := Phone{}
phone.SetName("Pixel")
UseDevice(&car)
UseDevice(&phone)
} Go does not support inheritance in any way, so Car and Phone will never be a Battery or a Meta. Go does support composition, but we have to differentiate composition from embedding because classical composition simply describes that Car and Phone have a battery property(component), where embedding means that Car and Phone do have a battery, but because we embedded it, we intentionally wanted Car and Phone to do BatteryPowered things. And since we added Meta to Car and Phone, they are also Named, and being both Named and BatteryPowered means they are a Device. I admit that the example is arbitrary and contrived, but the idea is that embedding is not truly inheritance or composition, and the main problems arising from it is trying to perceive it as either. Such is the case with Alice and eye color. If we apply this slight change in our way of thinking to that scenario, it becomes obvious that embedding Eyes into Person doesn't quite make sense: "Person is Colorful because it has Eyes". Instead, Eyes should be a component property of Person, distinguishing a clear difference between embedding and classic composition. |
@codydbentley Your example could be reduced to the following. It is done without embedding and it ends up being a lot simpler. There are fewer data types. They are flat and have fewer dependencies.
Looking back, my early Go codes use plenty of embedding. Being familiar with other OO languages, I used embedding mostly to simulate inheritance. Soon I learned that embedding does not work like inheritance at all. Like inheritance, embedding has method propagation. Unlike inheritance, the propagated methods do not refer to the 'child' object. On the other hand, composition does not need method propagation. It ends up being weird if used with method propagation. I agree with you that embedding is neither an "is-a" nor a "has-a". It is like a half-hearted implementation of inheritance and I cannot find the words to describe the relationship that embedding conceptually describes. As I gain experience with Go, my later codes do not use embedding. I do not intentionally avoid the feature. I just do not find it useful. Things are simpler without embedding. However, as I said before, it may not be practical to remove embedding. Plenty of codes will be broken, including some that I wrote during my early Go adventure and the libraries that I still use now. So I suppose we should just let embedding stay for backward compatibility purposes. |
Go's embedded types are prototype-based inheritance, like what JavaScript has. In JavaScript, when you assign Go types can have a list of prototypes, instead of just one, as embedded types. Instead of resolving Go's version of attributes, methods, at runtime, they're resolved at compile time. It's the same idea. Go has inheritance. It's always had inheritance (just like exceptions). It just doesn't call it that. It has prototype-based inheritance, not class-based inheritance. The whole point of inheritance is to reuse code. We use prototype-based inheritance to lift existing code into new implementations of interfaces, without the inflexible straitjacket of class-based inheritance. |
All I know is that Go by trying to be "dead-simple" in its, "we're not an object oriented language, but we have objects approach", created somewhat of an issue with code reuse by being obtuse about the best way to handle extensions. Inheritance in my opinion circumvents alot of these issues if you just allowed the types to inherit and extend functionality, it's just more straight-forward, and most inheritance hierarchies should only go 1-2 levels deep. But in Go the solution was stated above by embedding interfaces, which is just a roundabout away of getting polymorphism and extensibility. But as for the forwarding methods solution, you're generating a lot of wrapper interfaces for handling every composition, do you really want to do that. If you do that's fine but you the developer or team always has the option to say this is our style and implementation. And I like that Go has those options. In my opinion my judgment is the opposite, introduce inheritance as another optional feature.
|
Go has a form of prototype-based inheritance, like JavaScript, except instead of being limited to one inherited value, there can be many (embedded structs). This was intentional, although perhaps the Go designers didn't think of it as "inheritance". Go inheritance (code reuse) uses composition: you inherit a method set from an embedded type, then intermingle your own methods among them. The inherited methods are implemented by the embedded value. |
There is a significant difference between Javascript's inheritance and Go's "inheritance". In Javascript, the keyword this refers to the current object. In Go, the method receiver refers to the originating object. In the case of method inheritance, the Javascript's version will refer to the child object, while the Go's version will refer to the parent object. Inheritance has been a mainstay in the programming world for decades and many people are familiar with how inheritance works. When people look at Go's embedding, they start thinking "Oh! This is inheritance", and there is a danger in treating Go's embedding as inheritance. Go's embedding is a crippled version of inheritance. It is best to think of it as a tool to copy and paste fields and methods from one struct to another. Don't attach any other meaning to it (eg. whether a Student is a Person, or a Student belongs to a Class). To the unwary, Go's embedding can be a pitfall. When it comes to solving inheritance problem, Go's dynamic interface does a better job in flattening the tall hierarchy issue than embedding does. In fact, embedding encourages some sort of hierarchy. Just like inheritance, with embedding, the definition of a type may get split up across several types and modules, leading to a fragmentation of code logic. You want a banana, but you must find the gorilla holding the banana and the jungle holding the gorilla, etc. There is also a visibility issue where it is impossible to make the embedded struct private. In short, embedding has all the inheritance warts, solves none of them, and does not offer the inheritance's full benefits. It is also a non-essential feature that you can live without. I am sure, implementation-wise, it is also complex and presents certain challenges for future language changes. I can imagine the amount of work involved to get generics to play nicely with embedding. I understand that it is impossible to remove embedding while maintaining backward compatibility with Go1. I just want to point out that embedding is the least valuable feature in Go. |
I'd disagree. It's quite a valuable feature in Go alongside Interfaces, and unlike Inheritance it allows for some better clarity of the scope and methods. That is, since attaching methods to a type requires specifying the type being worked on, it's clear what the scope is - whether pointer receiver or value receiver even. About the only wart is determining which methods take priority when multiple embedded types have the same method attached - but that's easily resolved by attaching a new method on the new type to determine the behavior, and even explicitly call the appropriate attachments for the embedded types - they can still be individually accessed and resolved just by scoping what is being worked on. |
I don't understand what you're saying here. In JavaScript, "this" refers to the head of the inheritance list. In Go, the receiver refers to the root of the inheritance tree. If a method isn't defined on the head/root, then the ancestors are searched for the first match. It's the same idea.
Go takes great pains to distance itself from how things are done in other languages, like class-based inheritance and exceptions, even eschewing those terms as much as possible. There are no "extends" or "inherits" keywords. When someone is new to Go, they should learn the language, not blindly assume that everything is the same as another language. https://go.dev/ref/spec is freely available to all.
Go does not have explicit type hierarchies. The point is to focus on method sets, and how to assemble them, not on taxonomies. Go uses prototype-based inheritance to allow you to reuse implementations by assembling them into larger components that implement interfaces. This avoids the general problem that class-based inheritance shares with global variables: it's difficult to reason about how variable "layers" interact with each other in "both" directions.
You can embed an unexported type.
So is class-based inheritance. C was the biggest language in the world for a long time. Go is a descendent of C.
I don't agree. Complex types are. ;) |
@willfaught I appreciate most of your latest post but I keep thinking that you should use the term prototype-based inheritance more carefully. JavaScript supports prototype-based inheritance. Go supports subtyping (via interfaces) and composition, but no form of inheritance whatsoever. Claiming otherwise will likely just breed more confusion. |
@jub0bs I linked to the definition of prototype-based inheritance, and explained the analogy to JavaScript. What specifically do you disagree with? Just because the language doesn’t call it prototype-based inheritance, doesn’t mean it doesn’t have it; it’s an abstract concept. I identified it by name to respond to the argument that Go should have class-based inheritance: Go already has inheritance, of a different kind. |
@willfaught You write
Terms matter. We should agree on their precise meaning before intelligible discourse can take place. In particular, we shouldn't conflate two radically different concepts. Go simply has no concept of prototype as understood in the JavaScript world. The Go specification does not contain the words "prototype" or "inheritance". The word "inherit" appears only once, but in the negative:
The Go FAQ states there's no type inheritance and mentions nothing about prototype-based inheritance (or class-based inheritance, for that matter). If those authoritative resources don't sway you, I don't know what will... |
I agree that terms matter, but I disagree that it's wrong or confusing to correctly use an abstract term to refer to something usually called by another name. Go has "generics", but in computer science type theory, it's called parametric polymorphism. Both terms have been used interchangeably in discussions about the design of Go's generics. It's not improper, or confusing, to use one term over the other. It's the same case here. Go has prototype-based inheritance, but it calls it struct embedding. If you don't like that particular correct terminology, then don't use it or ignore it, but don't try to stop others from using it. As I said above, I only introduced this particular term to explain that Go already has inheritance, so adding class-based inheritance would not be orthogonal. In any other context, I wouldn't have even brought it up.
They're talking about class-based inheritance. 99% of the people who want inheritance, like the OP, want class-based, and don't even know about prototype-based as an option. So they geared the Q&A around that. As I suggested above, even the Go team might not have realized that struct embedding is a kind of prototype-based inheritance, which could also explain why it's not addressed there.
I've already addressed this point. |
I agree with willfaught's assertion ... given how Go's embedded types work, things behave much like a prototype based inheritance. I don't see how there is any imprecision or inaccuracy with such an observation. For fun, some while ago I attempted to mimic JavaScript's prototype behavior in Python and Julia ... since both languages give the programmer some control on how an object's "API" works. You can build objects via successive composition ... but then recursively forward methods. The easiest implementation is that you terminate the recursion upon finding the first "match" ... just as willfaught has already discussed. While certainly one can claim that Go doesn't possess traditional class-based inheritance ... certainly, the observation can still be made that embedded-types do, in fact, permit a type of inheritance that is prototype-like (how's that for a change in terminology). |
There's nothing wrong with class-based inheritance. No one has been able to prove to me that something is wrong with it. Inheritance isn't evil. It's only evil because of the way we use it. A lot of software engineers start out by creating parent classes first before sub classes which is how inheritance can easily go wrong as it is akin to premature abstraction and the abuse of the DRY principle. One should take a bottom-to-top approach by creating sub classes first before creating parent classes as this allows you to focus on only the logic/behavior and data boxes you require immediately. Read more here So, while i do not support removing struct embeddings going forward (for Go v2) as the OP has agreed to not pursue such. I feel that avoiding it entirely leads simpler code. |
Language newcomer here. However, I will posit that Go definitely does not implement inheritance, prototypal or otherwise. It simply uses embeddings to achieve polymorphism through composition. Inheritance and composition are two different tactical approaches to achieve polymorphism. Another way to look at it would be to consider that polymorphism is a semantic relation within your programs while sub classing (inheritance) and embeddings (composition) are syntactic language features that allow you to achieve that state of operability. There is no inherent benefits to either approach over the other. Ultimately it is a matter of preference. The GOF guidance that seems to form the basis for Go's implementation details is even stated as a preference rather than a general rule. The problems that I'm seeing argued throughout this thread are actually Liskov violations that can be committed within either paradigm. The bottom line is that language features don't make good OO software developers. Rather, good OO programmers understand how to employ language features correctly. With that being said, the only pro/con of this proposal that I can see is as follows: Pro: adding inheritance reduces barriers to entry for OO developers that hail from other stacks. More devs usually equates to a healthier and more vibrant ecosystem. Con: adding inheritance increases the complexity of the language. There's now more than one way to "skin the cat" when it comes to polymorphism in the Go language. While there's no real counterargument to the pro, there is one to the con. Technically, the language could include inheritance as a way of introducing simpler subtyping graphs. The current mechanism of embeddings allows for something akin to multiple inheritance. While admittedly a powerful language feature, it can absolutely be maddening in the wrongs hands. Subclassing can be enforced in isolation within project teams that don't want to open that can of worms. Additionally, classes can be used to "disable" the automagic of embeddings for similar reasons. Case in point: I'm currently on a quest to determine how the compiler addresses name collisions between methods/attributes on multiple embeddings within the same struct. I only happened upon this thread while researching that topic because it actually isn't called out in the literature that I've read so far. I'm sure that there's and answer but I imagine it'll either be some esoteric convention or a outright compiler error. There may also be a way to resolve the name collision when they occur. In any case, single inheritance through subclassing ensures that such scenarios never occur in the first place - which may be appropriate for some teams. Regardless, I don't see any wisdom in just ripping out embeddings entirely. They are not inherently evil in any way. The problems that they've been blamed for either: exist in inheritance schemes as well; are really a complaint about "magic" language features in general; or, are actually attributable to the support for multi embeddings rather than to embeddings in-and-of themselves. I'd actually propose that subclassing be implemented as design time syntax sugar that the compiler translates into embeddings and avoid changes to the runtime instructions entirely - but that's just me. |
As noted, this change would not be backward compatible. We have no plans to ever change Go such that existing programs stop working. Therefore, this is infeasible. Closing. |
I would like to propose the removal of embedded struct in Go 2.x, because it does not solve inheritance problems, and the alternatives may actually be better.
First, let us examine the pros and cons of inheritance (more specifically, implementation inheritance). Inheritance groups common functionalities into the base class. It allows us to make a change in one place (instead of being scattered everywhere), and it will be automatically propagated to the derived classes. However, it also means the derived classes will be highly coupled to the base classes. The base class implementor, who does not need to know anything about the derived classes, may inadvertently break the derived classes when making changes to the base class. In addition, inheritance encourages a type hierarchy. In order to understand a derived class, one need to know its base classes (which includes its immediate parents, its grandparents, its great grandparents, etc.). It gives us the classic OOP problem where in order to get a banana, you need the monkey and the whole jungle. Modern OOP proponents now encourage "composition over inheritance".
Go's embedded struct is unique. At a glance, it appears to be a composition. However, it behaves exactly like the classic inheritance, including the pros and cons of inheritance. The base struct implementor may inadvertently break the derived structs. In order to understand a derived struct, one must look up the definition of its base struct, creating a hierarchy of types. Thus, Go's embedded struct is actually inheritance (although it is a crippled one).
I say it is a crippled inheritance because Go's embedded struct does not provide the same flexibility as the actual inheritance. One such example is this:
driver.Drive(s60.Volvo.Car.Vehicle)
Even though s60 is a vehicle, in Go, you need to get to the actual base class in order to use it as an argument.
If the Go's Team considers keeping this inheritance property, I say they should either go all the way with inheritance, or scrap it altogether. My proposal is to scrap it.
Here are my reasons for scrapping it:
You can do this
Let me know what you think.
Thanks.
Henry
The text was updated successfully, but these errors were encountered: