英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论