继承 java
Go doesn’t have a concept of class or have a class-based inheritance. Go is a bit different than the regular object-oriented languages.
Go没有类的概念,也没有基于类的继承。 Go与常规的面向对象语言有点不同。
Go has a unique feature called embedded fields in the struct(More like composition). Using those we can reuse the code, it is pretty much similar to what Inheritance provides in other languages.
Go具有一个独特的功能,称为结构中的嵌入字段(更像是组合)。 使用这些代码,我们可以重用代码,它与Inheritance在其他语言中提供的代码非常相似。
The Embedded field is a special field, a field without a field name. Let’s have a look at the below example :
嵌入式字段是一个特殊字段,没有字段名称的字段。 让我们看下面的例子:
As mentioned in the above example: Animal is an embedded field in the parrot struct. The Animal struct is behaving like a base struct and Parrot struct has inherited all the fields and methods of it. Let’s have a look at our main function: line 30: We are calling a method Eat which is overridden by parrot struct. line 33: We are calling a method Sleep which is a method of the animal struct(The parent struct).line 35: We are using field(Weight) of the Animal as it is of Parrot field.
如以上示例所述:Animal是鹦鹉结构中的嵌入式字段。 Animal结构的行为类似于基本结构,而Parrot结构继承了它的所有字段和方法。 让我们看一下我们的主要功能:第30行:我们正在调用Eat方法,该方法被鹦鹉结构覆盖。 第33行:我们正在调用Sleep方法,它是动物struct(父结构)的方法。第35行:我们正在使用Animal的field(Weight),因为它是Parrot字段。
But Is there a benefit of using embedded fields? Yes, the similar benefits we get with the below design principles:
但是使用嵌入式字段有好处吗? 是的,我们通过以下设计原则获得了类似的好处:
Favor composition over inheritance
偏爱继承而不是继承
Many times we require our code to be more flexible and change its behavior at the run time. Inheritance is a very tightly coupled feature, as it is defined at compile time we can’t change the class behavior at run time. With composition, we can always change the class behavior with dependency injection or setters.
很多时候,我们要求代码更加灵活,并在运行时更改其行为。 继承是一个非常紧密耦合的功能,因为它是在编译时定义的,因此我们无法在运行时更改类的行为。 通过composition,我们始终可以使用依赖项注入或setter更改类行为。
As in the above example, we could have embedded an interface in the Parrot struct(Yes, the Embedded feature is available for both struct and interface. We could have an animal interface embedded in the parrot struct).
如上例所示,我们可以在Parrot结构中嵌入一个接口(是的,该结构和接口都可以使用Embedded特性。我们可以在Parrot结构中嵌入一个动物接口)。
type Animal interface { Eat() Sleep()}Then we can change the Parrot behavior at runtime by setting the Animal field with any struct satisfying the Animal Interface. For example:
然后,我们可以通过使用满足动物界面的任何结构设置动物字段来更改运行时的鹦鹉行为。 例如:
翻译自: https://medium.com/@amitj975/inheritance-in-go-94d47d52b577
继承 java