gRPC generic type in Golang

tommady
honestbee-tw-engineering
1 min readNov 28, 2018

Recently I designed a SQL database server by receiving gRPC After that I finished the basic database actions such like Select, Insert, Update, etc.

The gRPC uses google protobuf as transmit format by default and it’s not easy to figure out how to use generic type like Void in C or interface{} in Golang.

After some head scratching, I found out there is a type in protobuf named Value in json mapping section so I use it in normal Message Type.

Codes are in my github.

First in Protobuf file import:

import "google/protobuf/struct.proto";

and define any arg by using:

google.protobuf.Value

Second in Server code import:

import "github.com/golang/protobuf/ptypes/struct"

define and use a reply like:

Third in Client code import the same as Server then define and use a request like:

The result will be:

2016/07/25 20:12:57 Str: string Generic!!!
2016/07/25 20:12:57 Number: 3345681.141590

WALA~

Conclusion

By using gRPC this way, we can easily complete the Generic Type. Since protobuf version 3 is still under developing, I am not sure there will be a better way to do this in Golang, hope that day will come soon!

--

--