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

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

问题描述

查看下面显示的G​​o文档,我无法理解接收者和参数之间的区别:

  func 
文件名:= p.Title +.txt
返回ioutil.WriteFile(文件名,p.Body,0600)
}




此方法的签名为:
这是一个名为save的方法,它的接收者p,一个指向
页面的指针。它不接受任何参数,并返回一个类型为error的值。


解决方案

这个在C#中: xf(a,b,c)接收者是 x 和参数是 a b c 。当函数被执行时,参数引用参数的副本。接收者和参数之间的重要区别在于,当接收者是呼叫站点的接口类型时,被调用的函数是动态而不是静态确定的。

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)
 }

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.

解决方案

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.

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

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