The argument in golang RPC call

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

The argument in golang RPC call

问题

在RPC处理函数中,我省略了第一个参数,如下所示:

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

在调用方的代码中:

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

因为我在GetName方法中不需要第一个参数,所以省略了它的名称,然而,我得到了以下错误信息:

gob: type mismatch in decoder: want struct type

我将GetName方法改为GetName(id int, reply *StructObj),问题就解决了。我想知道为什么会出现这个问题?

英文:

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

得分: 7

你在Go语言中遇到了一个棘手的函数定义语法问题。你不能有一个无名参数,而且你可以给参数命名为intfunc f(x, y, z Type)是一种声明三个变量都是Type类型的快捷方式。例如,func f(int, x string)声明了一个接受两个字符串f函数,其中一个恰好被命名为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")
}

当你运行它,输出结果是:

int is: foo
x is: bar

是的,这有点令人费解。我从来没有听说过具体的思考过程,但也许他们保留了内置类型名称的未保留状态,这样他们就可以在不破坏已经存在的代码的情况下引入新的内置类型。

无论如何,这意味着你的第一个函数定义实际上并不接受一个int和一个*StructObj,而是接受一个名为int*StructObj和另一个名为reply的参数。所以net/rpc包中的错误消息实际上意味着客户端传递了一个0,而它期望的是一个*StructObj。非常有趣。

英文:

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.

huangapple
  • 本文由 发表于 2014年9月16日 13:41:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/25861389.html
匿名

发表评论

匿名网友

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

确定