Inheritance 围棋中的继承
为什么没有类型继承呢Inheritance 围棋中的继承,inheritance,go,Inheritance,Go,为什么没有类型继承呢 (定义对象类时,所定义的任何子类都可以继承一个或多个通用类的定义的概念)这是语言创建者在 面向对象编程,至少在最知名的语言中,涉及到太多类型之间关系的讨论,这些关系通常可以自动派生。Go采取了不同的方法 与要求程序员提前声明两种类型是相关的不同,在Go中,类型自动满足指定其方法子集的任何接口。除了减少簿记,这种方法还有真正的优势。类型可以同时满足多个接口,而不需要传统多重继承的复杂性。接口可以是非常轻量级的,具有一个甚至零个方法的接口可以表达有用的概念。如果出现新的想法,可
(定义对象类时,所定义的任何子类都可以继承一个或多个通用类的定义的概念)这是语言创建者在 面向对象编程,至少在最知名的语言中,涉及到太多类型之间关系的讨论,这些关系通常可以自动派生。Go采取了不同的方法 与要求程序员提前声明两种类型是相关的不同,在Go中,类型自动满足指定其方法子集的任何接口。除了减少簿记,这种方法还有真正的优势。类型可以同时满足多个接口,而不需要传统多重继承的复杂性。接口可以是非常轻量级的,具有一个甚至零个方法的接口可以表达有用的概念。如果出现新的想法,可以在事后添加接口,或者在不注释原始类型的情况下进行测试。因为类型和接口之间没有明确的关系,所以没有要管理或讨论的类型层次结构
另请参见:。如果需要继承以实现可重用,此示例显示了我如何重用形状界面的宽度/高度
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's 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())
}
结果:
&{{4 6}}
width: 4
in Rectangle.GetHeight
in WidthHeight.GetHeight
height: 6
in Rectangle.GetHeight
in WidthHeight.GetHeight
area: 12
我认为嵌入与定义非常接近:
package main
import "net/url"
type address struct { *url.URL }
func newAddress(rawurl string) (address, error) {
p, e := url.Parse(rawurl)
if e != nil {
return address{}, e
}
return address{p}, nil
}
func main() {
a, e := newAddress("https://stackoverflow.com")
if e != nil {
panic(e)
}
{ // inherit
s := a.String()
println(s)
}
{ // fully qualified
s := a.URL.String()
println(s)
}
}
多重继承通常指的是继承多个类,而不是实现多个接口,而且永远都不好。在GO中实现多个接口是可能的,并且在传统语言中如C++和java没有任何麻烦,并且在适当的时候是好的/必要的。多重继承是可能的C++,但皱眉(除了所有,但只有一个类作为界面-即没有属性或方法暗示)。这在Java中是非法的,所以即使你想调皮,也不能调皮:)