英文:
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语言中遇到了一个棘手的函数定义语法问题。你不能有一个无名参数,而且你可以给参数命名为int
,func 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论