从protobuf消息中获取枚举值。

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

Get the enum value out from protobuf messages

问题

这是一个protobuf消息定义:

message People {
  enum PeopleName {
    Alice = 100;
    Bob = 101;
    Cathy = 102;
  }
  optional PeopleName name = 1;
}

我想根据我创建的一些字符串填充name字段。例如,在golang中:

str := "Cathy"

我该如何填充protobuf消息中的"name"字段?

英文:

Here is a protobuf message definition:

message People {
  enum PeopleName {
    Alice = 100;
    Bob = 101;
    Cathy = 102;
  }
  optional PeopleName name = 1;
}

I would like to populate the name field based on some strings I created. E.g. in golang:

str := "Cathy"

How can I populate the "name" in the protobuf message?

答案1

得分: 34

Go的protobuf生成器会生成一个枚举名称到值(以及相反)的映射。你可以使用这个映射将字符串转换为枚举值:

str := "Cathy"

value, ok := People_PeopleName_value[str]
if !ok {
    panic("invalid enum value")
}

var people People
people.Name = People_PeopleName(value)
英文:

The Go protobuf generator emits a map of enum names to values (and vice versa). You can use this map to translate your string to enum value:

str := "Cathy"

value, ok := People_PeopleName_value[str]
if !ok {
    panic("invalid enum value")
}

var people People
people.Name = People_PeopleName(value)

答案2

得分: 4

使用proto3,从枚举值到字符串,你可以直接使用:

name.String()
英文:

With proto3, from enum value to string, you can directly use:

name.String()

huangapple
  • 本文由 发表于 2017年5月5日 01:58:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/43789785.html
匿名

发表评论

匿名网友

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

确定