英文:
Convert golang protobuf enum from int32 to string
问题
我正在面临一个问题,我定义了一个枚举类型的protobuf,但它的值是int32类型的。现在我想以某种方式将所有的protobuf定义更改为字符串类型,或者在不更改protobuf的情况下进行任何代码修改。
枚举定义如下:
enum TimeUnit {
seconds = 0;
minutes = 1;
hours = 2;
days = 3;
months = 4;
}
message CacheDuration {
uint32 Value = 1;
TimeUnit Units = 2;
}
我从生成的代码中得到的结果是:
这是前端要使用的返回值。所以他们会看到Units的值是int32类型的,就像这样:
服务之间通过生成的结构化protobuf进行通信。
我想将其更改为:
"Units":"days"
谢谢。
英文:
I am facing with the problem that protobuf I defined enum but its value is int32
Now I want someway or somehow to change all the protobuf defined to string
Or any code-hack for doing it in gateway without changing the protobuf.
Enum defined
enum TimeUnit {
seconds = 0;
minutes = 1;
hours = 2;
days = 3;
months = 4;
}
message CacheDuration {
uint32 Value = 1;
TimeUnit Units = 2;
}
What i got from generated code now is
And it is the return value for front end to use. So they would see the value of Units = int32 like this:
The services communicate by generated struct protobuf.
I want to make it change to
"Units":"days"
Thanks
答案1
得分: 2
你可以在你的Go代码中使用String
方法:
generatedTimeUnitEnum.String() // 输出:days
英文:
You can use String
method in your go code:
generatedTimeUnitEnum.String() // output: days
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论