去接收方法调用语法混乱 [英] Go receiver methods calling syntax confusion

查看:156
本文介绍了去接收方法调用语法混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读有效之路,并在指针与值部分,在结束附近:

I was just reading through Effective Go and in the Pointers vs. Values section, near the end it says:


关于接收器的指针与值的规则是可以在指针和值上调用值方法,但只能在指针上调用指针方法。这是因为指针方法可以修改接收器;在值的副本上调用它们将导致这些修改被丢弃。

The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers. This is because pointer methods can modify the receiver; invoking them on a copy of the value would cause those modifications to be discarded.

为了测试它,我写道:

package main

import (
  "fmt"
  "reflect"
)

type age int

func (a age) String() string {
  return fmt.Sprintf("%d yeasr(s) old", int(a))
}

func (a *age) Set(newAge int) {
  if newAge >= 0 {
    *a = age(newAge)
  }
}

func main() {
  var vAge age = 5
  pAge := new(age)

  fmt.Printf("TypeOf =>\n\tvAge: %v\n\tpAge: %v\n", reflect.TypeOf(vAge),
    reflect.TypeOf(pAge))

  fmt.Printf("vAge.String(): %v\n", vAge.String())
  fmt.Printf("vAge.Set(10)\n")
  vAge.Set(10)
  fmt.Printf("vAge.String(): %v\n", vAge.String())

  fmt.Printf("pAge.String(): %v\n", pAge.String())
  fmt.Printf("pAge.Set(10)\n")
  pAge.Set(10)
  fmt.Printf("pAge.String(): %v\n", pAge.String())
}

即使文档说它应该'因为指针方法 Set()不能通过值var vAge 调用。我在这里做错了吗?

And it compiles, even though the document says it shouldn't since the pointer method Set() should not be invocable through the value var vAge. Am I doing something wrong here?

推荐答案

这是有效的,因为 vAge 寻址。请参阅通话中最后一段的语言规范:

That's valid because vAge is addressable. See the last paragraph in Calls under the language spec:


如果方法集(的类型)x
包含m并且参数列表可以分配给m的参数列表
,则调用xm()方法是有效的。如果x是可寻址的,& x的方法集包含m,则x.m()是(& x).m()的
简写。

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().

这篇关于去接收方法调用语法混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆