dongyi6845 2017-05-13 12:31
浏览 8

Go方法调用速记规范适用性

From the Calls section of Go spec: https://golang.org/ref/spec#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()

My program.

package main

import (
    "fmt"
)

func main() {
    p := Point{2, 3}

    p.FakeScale(10)
    fmt.Println(p)

    p.RealScale(10)
    fmt.Println(p)
}

type Point struct {
    x int
    y int
}

func (p Point) FakeScale(s int) {
    p.x *= s
    p.y *= s
}

func (p *Point) RealScale(s int) {
    p.x *= s
    p.y *= s
}

Here is the output.

{2, 3}
{20, 30}

My question is specifically about this part of the spec.

If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()

My questions.

  1. Is the quoted part applicable to p.FakeScale(10)? My guess is "No" because although p is addressable, &p's method set does not contain FakeScale. p's method set contains FakeScale because it uses value receiver, but p's method set does not contain FakeScale, therefore this part of the spec is not applicable to p.FakeScale(10). Am I correct?
  2. Is the quoted part applicable to p.RealScale(10)? My guess is "Yes" because p is addressable and &p's method set contains RealScale by virtue of it using a pointer receiver. Therefore, this part of the spec is applicable to p.RealScale(10). Am I correct?
  3. Can you provide an example code where x.m() is valid but x is not addressable, and thus this part of the spec is not applicable?
  • 写回答

2条回答 默认 最新

  • dsuikgi9199 2017-05-13 13:11
    关注

    Hm. Also I begin to doubt my knowledge of English language but I will try to answer.

    You quoted 2 sentences from specification.

    1. Describes conditions for method to be valid.
    2. Describes shorthand for recievers of pointer types.

    Back to your question:

    You defined 2 methods for 2 types: first - reciever of Point and second - receiver of pointer to Point.

    Obviously, shorthand definition for pointer types is not applicable for non-pointer types.

    So, you're correct in your questions 1 or 2.

    And your third question is in fact question 1: FakeScale is valid method but method with non-pointer type in receiver, so shorthand definition is not applicable.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测