【发布时间】:2016-06-04 17:22:15
【问题描述】:
我又要通过Tour of Go了,我被这个Methods Module搞糊涂了
简而言之,指定类型Vertex 以及带有指针接收器的函数
type Vertex struct {
X, Y float64
}
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
这里不用担心。然而,我的困惑来自主函数,它似乎允许值类型调用指定指针接收器的方法。
func main() {
v := Vertex{3, 4}
v.Scale(10)
// v's fields have changed
}
我检查了 v 的类型只是为了确定
fmt.Printf("v's type is %T\n", v)
// v's type is main.Vertex
为什么允许这样做? v 不应该是调用 Scale 方法的指针,例如v := &Vertex{3, 4}
【问题讨论】:
-
几张幻灯片后您就有了答案:tour.golang.org/methods/6
-
@T.Claverie,我刚刚看到并发布它作为答案,哈哈!
-
允许,因为语言规范是这样说的。
标签: function pointers methods go