Golang中的interface{}参数如何判断是传值还是传指针

huangapple go评论87阅读模式
英文:

Golang interface{} parameter how to judge pass value or pass pointer

问题

当我学习Go语言时,我对interface{}参数感到困惑。

例如,我使用net/rpc包。

接口定义如下:

// 描述:Call调用指定的函数,等待其完成,并返回其错误状态。
func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) error

当我将reply参数作为值传递时,程序会报错:rpc call error:reading body gob: attempt to decode into a non-pointer

那么,如何区分何时应该传递指针或传递值给接口呢?

英文:

When I learn go language, I was confused by interface{} parameter

for example, I use the net/rpc

the interface is:

// description: Call invokes the named function, waits for it to complete, and returns its error status.
func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) error

I just pass the reply parameter as value, the program will error:
rpc call error:reading body gob: attempt to decode into a non-pointer

so how to distinguish when I should pass pointer or pass value for the interface.

答案1

得分: 1

interface{}类型用于函数参数表示,您可以将任何类型的值传递给该参数。这是因为所有类型都实现了interface{}(空接口)。这也包括指针类型。

因此,您不能仅根据该参数的interface{}类型声明来判断是否需要传递指针或值。因为它将接受两者。所以,您需要查阅具体函数的文档,看作者的期望是什么。

在您的情况下,错误定义在https://golang.org/src/encoding/gob/decoder.go中。正如错误所说,解码器需要一个指向reply参数的指针。否则,reply将无法返回给调用者。

英文:

The interface{} type for a function argument indicates, that you can pass value with any type to that argument. That is because all types implements interface{} (empty interface). This also includes a pointer type as well.

Because of that, You cannot judge whether you need to pass pointer or value based on the interface{} type declaration of that argument alone. Because It will accept both. So, you need to consult documentation of the specific function, and see what author expects.

In your case, the error is defined at https://golang.org/src/encoding/gob/decoder.go As the error says, decoder need a pointer for the reply parameter. Otherwise, the reply won't get back to the caller.

huangapple
  • 本文由 发表于 2016年4月10日 23:08:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/36531421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定