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 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题