Home  >  Article  >  Backend Development  >  How to fix redefined fields in protocol buffer definition in Go?

How to fix redefined fields in protocol buffer definition in Go?

王林
王林forward
2024-02-06 11:39:04612browse

如何修复 Go 中协议缓冲区定义中重新定义的字段?

Question content

I'm building a gRPC client using the provider's .proto file, and I have several enumerations containing values ​​of the same name.

syntax = "proto3";

enum Color {
  NONE = 0;
  BLUE = 1;
}

enum Style {
  SOLID = 0;
  NONE = 1;
}

So when I generate the Go service for the .proto file and try to run it, I get the following error:

...\deal.pb.go:460:2: NONE redeclared in this block
...\deal.pb.go:105:2: other declaration of NONE

I tried moving enums within messages, for example moving colors within shapes, and expected this to provide a different namespace. But it's no use. The generated code declares constant blocks and the message does not provide the name spacing I would like. This works for C#.

const (
  NONE Shape = 0
  BLUE Shape = 1
)

Any ideas on how to solve this problem?


Correct answer


You should rename the enum values ​​because the main problem in the provided code is that the generated Go code contains two names named NONE constants, one from the Color enumeration and one from the Style enumeration. This causes a naming conflict because in go, all constants in the generated protobuf code exist at the package level, making them global variables of the package. So, maybe you can try this:

enum Color {
  COLOR_NONE = 0;
  COLOR_BLUE = 1;
}

enum Style {
  STYLE_SOLID = 0;
  STYLE_NONE = 1;
}

The above is the detailed content of How to fix redefined fields in protocol buffer definition in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete