去接收方法调用语法混乱

编程入门 行业动态 更新时间:2024-10-15 16:19:32
本文介绍了去接收方法调用语法混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

去接收方法调用语法混乱

本文发布于:2023-11-25 04:57:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628422.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   混乱   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!