dongluyi5123 2013-02-17 22:31
浏览 15
已采纳

方法接收者的歧义

Working on the go tour today. I noticed that I could pass struct literals to methods associated with pointer to structs, and vice versa. Why is this allowed?

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)
}

Output:

&{3 4}
&{15 20}
{3 4}
{15 20}
  • 写回答

1条回答 默认 最新

  • duanmin0941 2013-02-17 22:48
    关注

    See Method sets:

    A type may have a method set associated with it (§Interface types, §Method declarations). The method set of an interface type is its interface. The method set of any other type T consists of all methods with receiver type T. The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T). Further rules apply to structs containing anonymous fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique method name.

    The method set of a type determines the interfaces that the type implements and the methods that can be called using a receiver of that type.

    EDIT:

    See also Calls:

    A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m():

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序