【发布时间】:2018-07-06 22:18:49
【问题描述】:
我目前正在学习 Go 中的接口,但我被这段代码卡住了:
package main
import (
"fmt"
"math"
)
// CommonMath is a common interface for math types
type CommonMath interface {
Abs() float64
}
// Float64 is a custom float64 type
type Float64 float64
// Abs returns the modulus of objects implementing CommonMath
func (f Float64) Abs() float64 {
if f < 0 {
return -float64(f)
}
return float64(f)
}
// AbsSquared returns the square of objects implementing CommonMath
func AbsSquared(num CommonMath) float64 {
return num.Abs() * num.Abs()
}
func main() {
var f Float64
f = -5
type newF Float64
var newFloat newF
newFloat = 10.5
fmt.Println(f)
fmt.Println(f.Abs())
fmt.Println(AbsSquared(newFloat))
}
事实证明,它无法编译,因为newFloat 没有实现接口CommonMath。属于newF类型,是实现接口的自定义Float64类型,不知道怎么回事。为了让事情变得更奇怪,我将 newF 和 newFloat 的声明替换为以下内容,它们实现相同但作为结构:
type newF struct {
Float64
}
newFloat := newF{10.5}
突然之间,代码构建得非常好。这是否意味着只有结构体才能实现父类型的接口,因此不允许将类型newF直接声明为Float64?
【问题讨论】:
-
首先,Go 中没有继承,这可能是混淆的一部分。声明
newF的唯一原因是删除方法。如果您不想为newF创建新方法集,请不要使用新类型。 -
也许继承不是这个词,但派生结构确实实现了其父实现的接口。为什么其他类型不会发生这种情况?
-
没有任何东西可以“继承”方法。您的结构有一个嵌入的
Float64字段,并且这些方法会自动委托给Float64实现。请参阅 Effective Go 中的 embedding 和 language spec
标签: inheritance go interface