dongxi7609 2014-09-16 05:41 采纳率: 0%
浏览 107
已采纳

golang RPC调用中的参数

In the RPC handler function, I omit the first argument like:

func (self Handler) GetName(int, reply *StructObj) {
}

and in the calling side

var reply StructObj
client.Call("Handler.GetName", 0, &reply)

Because I do not need the first argument in the GetName Method, I omit its name, HOWEVER, I got:

gob: type mismatch in decoder: want struct type

I changed the GetName method to GetName(id int, reply *StructObj) and it works. I want to know why this happened?

  • 写回答

1条回答 默认 最新

  • dt3674 2014-09-16 06:10
    关注

    You hit a tricky aspect of function definition syntax in Go. You can't have an unnamed argument, and you can name an argument int, and func f(x, y, z Type) is a shortcut to declare all three variables to be of type Type. For example, func f(int, x string) counterintuitively declares an f that accepts two strings, one of which happens to be named int.

    package main
    
    import "fmt"
    
    func f(int, x string) {
        fmt.Println("int is:", int)
        fmt.Println("x is:", x)
    }
    
    func main() {
        f("foo", "bar")
    }
    

    When you run it, the output is

    int is: foo
    x is: bar
    

    Yes, that's a little mind-bending. I've never heard the specific thinking explained, but maybe they kept builtin type names un-reserved so they could later introduce new builtin types without breaking code that's already out there.

    Anyway, it means your first function definition doesn't actually accept an int and a *StructObj but a *StructObj named int and another named reply. So the error message from net/rpc actually means that the client passed a 0 when it expected a *StructObj. Pretty fun.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启