为什么带有指针接收器的方法在接收到值时仍然有效? [英] Why does a method with a pointer receiver still work when it receives a value?

查看:13
本文介绍了为什么带有指针接收器的方法在接收到值时仍然有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在玩围棋巡回赛中的练习 51.解释声称 Scale 方法在接收到 Vertex 而不是指向 Vertex 的指针时无效.

I was just playing with Exercise 51 in the Tour of Go. The explanation claims the Scale method has no effect when it receives a Vertex instead of a pointer to a Vertex.

然而,当我在 main<中将声明 v := &Vertex{3, 4} 更改为 v := Vertex{3, 4}/code> 输出中唯一的变化是缺少 & 来标记指针.

Yet when I change the declaration v := &Vertex{3, 4} to v := Vertex{3, 4} in main the only change in the output is the missing & to mark the pointer.

那么为什么 Scale 会改变它接收到的变量,即使该变量不是指针?

So why does Scale change the variable it receives even if the variable isn't a pointer?

推荐答案

它不接收"一个值.Go 是强类型的,因此如果在某处指定了指向 T 的指针,则指向 T (*T) 的指针是唯一可以作为此类类型位置的值发生的选项.

It does not "receive" a value. Go is strongly typed, so if somewhere a pointer to T is prescribed, a pointer to T (*T) is the only option which can happen as a value for such typed place.

魔术"在编译器中,它在某些条件下有效地重写"您的代码:

The "magic" is in the compiler which effectively "rewrites" your code under certain conditions:

方法调用 xm() 是有效的,如果(类型)x 的方法集包含 m 并且参数列表可以分配给m的参数列表.如果 x 是可寻址的并且 &x 的方法集包含 m,则 xm()(&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天全站免登陆