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

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

王林
Release: 2024-02-06 11:39:04
forward
704 people have browsed it

如何修复 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;
}
Copy after login

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
Copy after login

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
)
Copy after login

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;
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template