Skip to content
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

Closed
henryas opened this issue Sep 25, 2017 · 100 comments
Closed

proposal: spec: remove embedded struct #22013

henryas opened this issue Sep 25, 2017 · 100 comments
Labels
LanguageChange Suggested changes to the Go language LanguageChangeReview Discussed by language change review committee Proposal
Milestone

Comments

@henryas
Copy link

henryas commented Sep 25, 2017

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:

  1. It offers no benefits. Although it looks like a composition, it is not. It behaves like inheritance with all the flaws of inheritance. It offers less flexibility than the real inheritance for no apparent benefits.
  2. It does not take much effort to write forwarding methods. In fact, it may be better to do an actual composition without the embedded struct feature. The slight extra effort pays off in the long run.
  3. If you truly do not want to write forwarding methods, you may refactor common methods into functions that accept a common interface. You can achieve the same effect as inheritance without having to couple the types. For instance, instead of
type BaseDriver struct{}
func (b BaseDriver) Drive(vehicle Vehicle){}

type TructDriver struct{
   BaseDriver
} 

type TaxiDriver struct{
   BaseDriver
}

You can do this

func Drive(driver Driver, vehicle Vehicle) {}

Let me know what you think.

Thanks.

Henry

@griesemer griesemer added v2 An incompatible library change LanguageChange Suggested changes to the Go language Proposal labels Sep 25, 2017
@griesemer
Copy link
Contributor

(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.

@twitchyliquid64
Copy link

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 subwoofer as speaker plus wubdubdub. I agree this is the wrong approach when you have really long recievers and complex composition though, then interfaces are a much better option.

Looking at your alternative, which you wrote as:

func Drive(driver Driver, vehicle Vehicle) {}

Imagine the realistic case where Driver or Vehicle have obscure interface methods, and there are a lot of implementations of Driver and/or Vehicle. Even having forwarder methods as you propose is a lot of duplication to deal with for function spec changes to the forwarded method (less of a problem nowadays with smart search-and-replace with IDEs).

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).

@cznic
Copy link
Contributor

cznic commented Sep 25, 2017

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.

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.

@as
Copy link
Contributor

as commented Sep 25, 2017

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.

@valyala
Copy link
Contributor

valyala commented Sep 25, 2017

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 net.Conn and net.Listener methods thanks to method forwarding in these cases.

@ianlancetaylor ianlancetaylor changed the title Go 2.0: Proposal to Remove Embedded Struct proposal: Go 2: remove embedded struct Sep 25, 2017
@gopherbot gopherbot added this to the Proposal milestone Sep 25, 2017
@henryas
Copy link
Author

henryas commented Sep 25, 2017

@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:

type BaseDriver struct{}
func (b BaseDriver) Drive(vehicle Vehicle){}

type TruckDriver struct{
    BaseDriver
}

type CabDriver struct{
    BaseDriver
}

You have two alternatives. First, you can use the real composition and employ method forwarding, which would be as follows:

type TruckDriver struct{
    parent BaseDriver
}
func (t TruckDriver) Drive(vehicle Vehicle){
    t.parent.Drive(vehicle) //method forwarding
   //...or you may implement custom functionalities.
}

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:

type Driver interface {} //which may be implemented by TruckDriver, CabDriver, etc.

func Drive(driver Driver, vehicle Vehicle){} //Drive is usable by any kind of driver.

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.

@cznic
Copy link
Contributor

cznic commented Sep 25, 2017

It behaves exactly like inheritance. Changes to the base type is automatically inherited by the derived types.

It does not behaves like inheritance at all. Given

type T int

func (T) foo()

type U struct {
        T
}

var u U

u.foo() behaves exactly like u.T.foo() when there's no foo defined within U - that's composition, not inheritance. It's only syntactic sugar with zero semantic change. When (T).foo executes it doesn't have the slightest idea its receiver is emebded in some "parent" type. Nothing from T gets inherited by U. The syntactic sugar only saves typing the selector(s), nothing else is happenning.

@henryas
Copy link
Author

henryas commented Sep 25, 2017

@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.

@ianlancetaylor
Copy link
Member

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.

@as
Copy link
Contributor

as commented Sep 25, 2017

@henryas

Since I am expected to function as a human, it breaks my intended functionality.

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

BreatheFire(at complex128)

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.

@bcmills
Copy link
Contributor

bcmills commented Sep 26, 2017

The base struct implementor may inadvertently break the derived structs.

That claim is not obvious to me. Could you give some concrete examples?

@henryas
Copy link
Author

henryas commented Sep 26, 2017

@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.

@bcmills
Copy link
Contributor

bcmills commented Sep 26, 2017

It does not take much effort to write forwarding methods.

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 BaseDriver today and someone adds some new method to it (e.g. PayToll(amount Money) error), all of the embedders will now implement the expanded method set too. On the other hand, with explicit forwarding methods you must locate and update all of the embedders before you can (say) add that method to a corresponding interface type.

@henryas
Copy link
Author

henryas commented Sep 26, 2017

@bcmills The problem with automatic method implementation is that the people who write BaseDriver may not know the context in which BaseDriver are used by their derived drivers, and may inadvertently break the original assumption about the specific drivers. For instance, in your example, I may have certain drivers whom I may want them to pay toll using cash card that the company can control, rather than with cash. I may already have EnterTollRoad(card *CashCard) method in my driver. The changes you make to the BaseDriver just provided a way to circumvent the security measure I have in place for my specific driver.

@ianlancetaylor
Copy link
Member

@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.

@henryas
Copy link
Author

henryas commented Sep 26, 2017

@ianlancetaylor if you read my earlier posts, I did point out that ... well, I will summarize it again here:

  1. The base type, that is supposed to not need to know anything about the derived types, has the ability to alter the derived types and break the original assumption about them.
  2. The consumer of the derived types needs to know not only the derived types themselves, but also the base type. It introduces unnecessary coupling. The consumer of the derived types is now coupled to both derived types and the base types (and the base types' base types if the base types are also derived from other types). It makes the code fragile because a change to any of the base types will have a cascading effect to other parts of the code.

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.

@ianlancetaylor
Copy link
Member

@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 .

@henryas
Copy link
Author

henryas commented Sep 27, 2017

@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:

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.

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.

Inheritance

What 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.

type Parent struct{}
func (p Parent) GrowFinsAndSwim(){} //Parent is a fish

//The child is automatically a fish
type Child struct{
    Parent
}
func (c Child) TalkTo(person Person){} 

//A super fish that can talk to human
child.GrowFinsAndSwim()
child.TalkTo(person)

Now, what if we changed the Parent to be a bird.

type Parent{}
func (p Parent) GrowWingsAndFly(){} //Parent is now a bird

//The child now becomes a bird
type Child struct{
    Parent
}
func (c Child) TalkTo(person Person){} 

//A super bird that can talk to human
child.GrowWingsAndFly()
child.TalkTo(person)

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.

type Parent{}
func (p Parent) GrowWingsAndFly(){} //Parent is a bird

//The super bird
type Child struct{
    Parent
    gps GPS
}
func (c Child) GrowWingsAndFly(){} 

//Unlike the Parent, this super bird uses GPS to fly.
child.GrowWingsAndFly()

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:

type Child struct{
    *Parent
}

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?

Composition

Now, 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:

type Person struct{
    pencil Pencil
}
func (p Person) Write (book Book) {
    //do something with pencil and book
} 

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:

type Person struct{
    Pencil
}

type Pencil struct{}
func (p Pencil) Brand() string{}
func (p Pencil) Manufacturer() string{}

//Okay
person.Pencil.Brand()

//But ... Ouch!
person.Manufacturer()
person.Brand()

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.

Conclusion

Let'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.

@davecheney
Copy link
Contributor

Let's start by calling a spade a spade. Go's embedded type is inheritance

It is not.

The thing is why do it in a roundabout way if what you need is plain inheritance.

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.

@cznic
Copy link
Contributor

cznic commented Sep 27, 2017

@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.

@henryas
Copy link
Author

henryas commented Sep 27, 2017

@davecheney I am puzzled.

In Go value types satisfy the "is-a" relationship

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?

and interface types satisfy the "has-a" relationship.

type Pencil struct{}
type Person struct{
    pencil Pencil
}
func (p *Person) SetPencil(pencil Pencil){}
func (p *Person) Pencil() Pencil{}

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?

@davecheney
Copy link
Contributor

@cznic yup, that's about as clear as I can make it

@henryas

A Carpenter is a Person that build furniture. A Singer is a Person that sings" in Go value types?

A type Carpenters struct{ ... } is-a Carpenter nothing more, nothing less. A Carpenter cannot be assigned to any other named type in Go.

A type Person struct{ ... } fulfils the type Singer interface{ ... } because it has-a func (p *Person) Sing() { ... } method.

@davecheney
Copy link
Contributor

davecheney commented Sep 27, 2017

@henryas

Where does that leave embedded types? What is the relationship between the embedded and the embeddee?

There is no relationship. type Pencil struct { ... } has no knowledge that it has been embedded inside another type, and that embedding has no effect on its behaviour.

@davecheney
Copy link
Contributor

@henryas

The above code has no interface whatsoever, and yet the Person "has a" Pencil.

This is not correct, type Person struct { ... } has a method called Pencil() and a field called pencil. As pencil is not embedded into Person, this is neither inheritance, nor embedding.

@as
Copy link
Contributor

as commented Sep 27, 2017

In Go, proper composition should look like this:

type Person struct{
    pencil Pencil
}
func (p Person) Write (book Book) {
    //do something with pencil and book
} 

Go supports this already, at the risk of sounding sarcastic, these are just struct fields. The value of anonymous structs is that they propagate structure and function at the field level whereas inheritance propagates function at the type level. Inheritance is a crippled construct such that the structure can not be altered down the creek and the user has to deal with the contract defined in the base class.

@henryas
Copy link
Author

henryas commented Jul 4, 2019

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.

@lnashier
Copy link

lnashier commented Aug 29, 2019

@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.

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.

@ibraheemdev
Copy link

ibraheemdev commented Aug 30, 2020

@henryas @ianlancetaylor

Why not have an explicit forwarding shortcut instead to replace the automagic?
That way we could have all the benefits of embedding without the strong implicit coupling.

e.g.

type Person struct {
   Name string
   Age int
   Children []Person
}

type Programmer struct {
   Age int
   Skills []string
   FavoriteLanguage string
}

func (p *Programmer) HasSkill(skill string) bool {
   for _, sk := range p.Skills {
     if sk == skill {
         return true
     }
   } 
   return false
}

type ProgrammingParent struct {
   Person Person
   Programmer Programmer
}

forward *ProgrammingParent -> .Programmer(Skills,FavoriteLanguage,HasSkill)
forwardAll *ProgrammingParent -> .Person

Syntax could be improved, just to demo the idea.

I really like this idea. The delegate method in ruby on rails could also be looked at for implementation:

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.

@YamiOdymel
Copy link

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 User struct as a property and ended up like GraphQL with nested structs:

// ...
type GetUserResponse struct {
	User      User
	IsBlocked bool
}

// ...
type GetRelationshipResponse struct {
	User          User
	FriendedAt    time.Time
	MutualFriends int
}

@jub0bs
Copy link

jub0bs commented Jun 7, 2021

@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.

@henryas
Copy link
Author

henryas commented Jun 7, 2021

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.

@jub0bs
Copy link

jub0bs commented Jun 7, 2021

@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 context package, for just one example.

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.

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.

it may be clearer to have B.A.Characteristics() without embedding at all

But wouldn't this approach result in the same kind of coupling that you were decrying above? Clients of the B type could break as soon as A changes.

Embedding is like one weird vocabulary that you do not know where to use.

I respect your point of view, but you can't speak for the entire community.

@sircodemane
Copy link

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:

A is B because it has C, where A is a composed struct, B is an interface, and C is a component Struct. A can do B things because the C component was bolted on. Imagine this use case where Car/Phone is a Device because it has a Battery and Meta:

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.

@henryas
Copy link
Author

henryas commented Jul 23, 2021

@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.

type Battery struct {
	charge int
}

func (b *Battery) Charge(level int) {
	b.charge += level
}

func (b *Battery) Deplete(level int) {
	b.charge -= level
}

func (b Battery) GetCharge() int {
	return b.charge
}

type Car struct {
	name    string
	battery Battery
}

func (c Car) Name() string {
	return c.name
}

func (c *Car) SetName(name string) {
	c.name = name
}

func (c *Car) Battery() *Battery {
	return &c.battery
}

type Phone struct {
	name    string
	battery Battery
}

func (p Phone) Name() string {
	return p.name
}

func (p *Phone) SetName(name string) {
	p.name = name
}

func (p *Phone) Battery() *Battery {
	return &p.battery
}

type BatteryPowered interface {
	Name() string
	Battery() *Battery
}

func UseDevice(device BatteryPowered) {
	fmt.Printf("using %s\n", device.Name())
	device.Battery().Deplete(24)
}

func main() {
	car := Car{}
	car.SetName("Mercedes")
	car.Battery().Charge(100)
	phone := Phone{}
	phone.SetName("Pixel")
	phone.Battery().Charge(100)
	UseDevice(&car)
	UseDevice(&phone)

}

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.

@willfaught
Copy link
Contributor

Go's embedded types are prototype-based inheritance, like what JavaScript has.

In JavaScript, when you assign parent to myobj.prototype, then access an attribute myobj.attr, the runtime will first look for attr on myobj, then on parent, then on parent.prototype, and so on until the prototype chain is exhausted.

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.

@andewx
Copy link

andewx commented Aug 2, 2023

@bcmills The problem with automatic method implementation is that the people who write BaseDriver may not know the context in which BaseDriver are used by their derived drivers, and may inadvertently break the original assumption about the specific drivers. For instance, in your example, I may have certain drivers whom I may want them to pay toll using cash card that the company can control, rather than with cash. I may already have EnterTollRoad(card *CashCard) method in my driver. The changes you make to the BaseDriver just provided a way to circumvent the security measure I have in place for my specific driver.

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.

type Truck from Car{
       tow_capacity float32
       //....
}

@willfaught
Copy link
Contributor

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. driver.Drive(s60.Volvo.Car.Vehicle) is how it's supposed to work, because driver.Drive only knows how to handle concrete vehicle types. If you want driver.Drive to handle an interface instead, then just do that, and have vehicles implement it.

@henryas
Copy link
Author

henryas commented Aug 12, 2023

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). ...

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.

@BenjamenMeyer
Copy link

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.

@willfaught
Copy link
Contributor

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.

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.

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 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'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.

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.

There is also a visibility issue where it is impossible to make the embedded struct private.

You can embed an unexported type.

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.

So is class-based inheritance. C was the biggest language in the world for a long time. Go is a descendent of C.

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 don't agree. Complex types are. ;)

@jub0bs
Copy link

jub0bs commented Aug 19, 2023

@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.

@willfaught
Copy link
Contributor

@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.

@jub0bs
Copy link

jub0bs commented Aug 19, 2023

@willfaught You write

Just because the language doesn’t call it prototype-based inheritance, doesn’t mean it doesn’t have it [...]

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:

A defined type may have methods associated with it. It does not inherit any methods bound to the given type [...]

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...

@willfaught
Copy link
Contributor

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.

The Go FAQ states there's no type inheritance

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.

If those authoritative resources don't sway you, I don't know what will...

I've already addressed this point.

@kidmoe667
Copy link

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).

@isocroft
Copy link

isocroft commented Feb 19, 2024

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.

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.

@hanserya
Copy link

hanserya commented Jun 16, 2024

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.

@ianlancetaylor ianlancetaylor added LanguageChangeReview Discussed by language change review committee and removed v2 An incompatible library change NeedsInvestigation Someone must examine and confirm this is a valid issue and not a duplicate of an existing one. labels Aug 6, 2024
@ianlancetaylor ianlancetaylor changed the title proposal: Go 2: remove embedded struct proposal: spec: remove embedded struct Aug 6, 2024
@ianlancetaylor
Copy link
Member

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.

@ianlancetaylor ianlancetaylor closed this as not planned Won't fix, can't repro, duplicate, stale Aug 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
LanguageChange Suggested changes to the Go language LanguageChangeReview Discussed by language change review committee Proposal
Projects
None yet
Development

No branches or pull requests