Go Inheritance

Why not Go has an Inheritance type.

(The notion that when defining a class of objects, any subclass that is defined can inherit the definitions of one or more general classes)

+5
source share
2 answers

This was answered by the creators of the language in the FAQ :

Object-oriented programming, at least in the most famous languages, involves too much discussion of the relationships between types, which can often be obtained automatically. Go takes a different approach.

Instead of requiring the programmer to declare in advance that the two types are related, in Go the type automatically satisfies any interface that indicates a subset of its methods. In addition to reducing accounting, this approach has real benefits. Types can satisfy many interfaces at once, without the complexity of traditional multiple inheritance. Interfaces can be very light - an interface with one or even null method can express a useful concept. Interfaces can be added after the fact, if a new idea comes or for testing - without annotating the original types. Since there is no explicit relationship between types and interfaces, there is no type hierarchy for management or discussion.

See also: Composition over the principle of inheritance .

+16
source

If you need inheritance for reuse, this example shows how I reuse the width / height of the form interface,

package main // compare to a c++ example: http://www.tutorialspoint.com/cplusplus/cpp_interfaces.htm import ( "fmt" ) // interface type Shape interface { Area() float64 GetWidth() float64 GetHeight() float64 SetWidth(float64) SetHeight(float64) } // reusable part, only implement SetWidth and SetHeight method of the interface // { type WidthHeight struct { width float64 height float64 } func (this *WidthHeight) SetWidth(w float64) { this.width = w } func (this *WidthHeight) SetHeight(h float64) { this.height = h } func (this *WidthHeight) GetWidth() float64 { return this.width } func (this *WidthHeight) GetHeight() float64 { fmt.Println("in WidthHeight.GetHeight") return this.height } // } type Rectangle struct { WidthHeight } func (this *Rectangle) Area() float64 { return this.GetWidth() * this.GetHeight() / 2 } // override func (this *Rectangle) GetHeight() float64 { fmt.Println("in Rectangle.GetHeight") // in case you still needs the WidthHeight GetHeight method return this.WidthHeight.GetHeight() } func main() { var r Rectangle var i Shape = &r i.SetWidth(4) i.SetHeight(6) fmt.Println(i) fmt.Println("width: ",i.GetWidth()) fmt.Println("height: ",i.GetHeight()) fmt.Println("area: ",i.Area()) } 

Result:

 &{{4 6}} width: 4 in Rectangle.GetHeight in WidthHeight.GetHeight height: 6 in Rectangle.GetHeight in WidthHeight.GetHeight area: 12 
+1
source

Source: https://habr.com/ru/post/1237636/


All Articles