Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The argument in golang RPC call

Tags:

go

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?

like image 604
Fionser Avatar asked Sep 16 '14 05:09

Fionser


People also ask

What is RPC call in Golang?

A Remote Procedure Call (RPC) is a subroutine in distributed computing. The remote implementation of RPC is similar to local calls but usually not identical.

What is RPC package?

Package rpc provides access to the exported methods of an object across a network or other I/O connection. A server registers an object, making it visible as a service with the name of the type of the object. After registration, exported methods of the object will be accessible remotely.

What is Gorpc?

Simple, fast and scalable golang RPC library for high load and microservices. Gorpc provides the following features useful for highly loaded projects with RPC: It minimizes the number of connect() syscalls by pipelining request and response messages over a single connection.


1 Answers

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.

like image 69
twotwotwo Avatar answered Oct 13 '22 08:10

twotwotwo