今天去旅游.我注意到我可以将struct literals传递给与指向结构的指针相关联的方法,反之亦然.为什么允许这样做?
package main
import (
"fmt"
)
type Vertex struct {
X, Y float64
}
func (v Vertex) Scale (f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func (v *Vertex) ScaleP(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
func main() {
v := &Vertex{3, 4}
vLiteral := Vertex{3, 4}
v.Scale(5)
fmt.Println(v)
v.ScaleP(5)
fmt.Println(v)
vLiteral.Scale(5)
fmt.Println(vLiteral)
vLiteral.ScaleP(5)
fmt.Println(vLiteral)
}
Run Code Online (Sandbox Code Playgroud)
输出:
&{3 4}
&{15 20}
{3 4}
{15 20}
Run Code Online (Sandbox Code Playgroud) 在这两个教程示例中,为什么带有指针接收器的方法在一种情况下满足接口而在另一种情况下不满足?
在示例#55中,类Vertex不满足Abser接口,因为方法Abs仅定义为*Vertex而不是Vertex:
type Abser interface {
Abs() float64
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
Run Code Online (Sandbox Code Playgroud)
错误消息是:
prog.go:22: cannot use v (type Vertex) as type Abser in assignment:
Vertex does not implement Abser (Abs method has pointer receiver)
Run Code Online (Sandbox Code Playgroud)
但是在示例#57中,即使定义了以下内容,该类也MyError满足error接口ok :Error()*MyErrorMyError
type error interface {
Error() string
} …Run Code Online (Sandbox Code Playgroud) go ×2