英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论