dtxzwdl08169 2016-04-10 15:08 采纳率: 0%
浏览 585

Golang接口{}参数如何判断传递值或传递指针

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条回答 默认 最新

  • doudie2693 2016-04-10 15:31
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3