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

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

问题描述

我刚刚在 Go Tour的练习51中玩法。该解释声明 Scale 方法在接收顶点时不起作用,而不是指向 Vertex



然而,当我更改声明 v:=& Vertex {3,4} v:=顶点{3,4} main 是缺少的& 来标记指针。为什么 Scale code>改变它收到的变量,即使变量不是一个指针?

解决方案

它不会接收 一个值。 Go是强类型的,所以如果指定了T指针,那么指向T( * T )的指针是唯一可以作为这种类型位置的值的选项。



魔术是在编译器中有效地重写你的代码在某些 conditions


方法调用 xm()如果 x (的类型)的方法集包含 m 和参数列表,则code>可以分配给 m 的参数列表。如果 x 是可寻址的,& x的方法集包含 m xm() code>是(& x).m()的缩写:

相关:方法集


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.

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.

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

解决方案

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:

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

Related: Method sets

这篇关于为什么具有指针接收器的方法在接收到值时仍然工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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