LoginSignup
4
0

More than 3 years have passed since last update.

protobufのenumをgolangの型(int32)に変換する

Posted at

protobuf で定義した enum を golang handler 内で int32型 に変換したかった時
「protobuf enum int 変換」みたいなワードでササっとググって出てこなかったのでメモとして残しておきます。

結論としては、単純に変換したい型で囲ってあげればよい。
type(enum type)

[protobuf]

service User {
  rpc PostUser(PostUserRequest) returns (User) {}
}

enum SexType {
  OTHER  = 0;
  MALE   = 1;
  FEMALE = 2;
}

message User {
  int64 id = 1;
  string name = 2;
  SexType sex = 3;
}

message PostUserRequest{
  string name = 1;
  SexType sex = 2;
}
[golang handler]
func GetUser(ctx context.Context, req *user.PostUserRequest) (*user.User, error) {
    var sex int32
    sex = int32(req.SexType)
    ... something ...
}
4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0