取自旅行团:
package main
import (
"fmt"
"math"
)
type Abser interface {
Abs() float64
}
func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f
a = &v
// v == Vertex != *Vertex -> exception
a = v
}
type MyFloat float64
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
但是,当func (v *Vertex) Abs() float64
变成时func (v Vertex) Abs() float64
,代码将编译:
package main
import (
"math"
)
type Abser interface {
Abs() float64
}
func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f
// Since *Vertex != Vertex, this shouldn't compile, should it?
a = &v
a = v
}
type MyFloat float64
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
为什么第二个示例运行?
类型*T
不是的子类T
,但是*T
的方法集将继承以下方法T
:
其他任何类型T的方法集都包含以接收者类型T声明的所有方法。相应指针类型* T的方法集是使用接收者* T或T声明的所有方法的集合(也就是说,它还包含方法T集)。
因此,如果T
符合特定的接口,则也是如此*T
。这就是为什么您可以在示例中*Vertex
为Abser
变量分配值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句