方法接收器和参数之间有什么区别? [英] What is the difference between a method receiver and parameter?

查看:51
本文介绍了方法接收器和参数之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看下面显示的G​​o文档,我在理解接收器和参数之间的区别时遇到了麻烦:

Looking at the Go documentation shown below, I'm having trouble understanding the distinction between receivers and parameters:

 func (p *Page) save() error {
     filename := p.Title + ".txt"
     return ioutil.WriteFile(filename, p.Body, 0600)
 }

此方法的签名为:这是一个名为save的方法,该方法将指向以下对象的指针作为其接收者p页 .它不带任何参数,并返回错误类型的值.

This method's signature reads: This is a method named save that takes as its receiver p, a pointer to Page . It takes no parameters, and returns a value of type error.

推荐答案

接收方就像C#中的 this :在 xf(a,b,c)中是 x ,参数是 a b c .执行该函数时,参数引用参数的副本.接收方和参数之间的重要区别在于,当接收方是调用站点上的接口类型时,要调用的函数是动态确定的,而不是静态确定的.

The receiver is like this in C#: in x.f(a, b, c) the receiver is x and the arguments are a, b and c. When the function is executed the parameters refer to copies of the arguments. The important difference between the receiver and parameters is that when the receiver is an interface type at the call site, the function to be called is determined dynamically rather than statically.

这篇关于方法接收器和参数之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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