protobuf icon indicating copy to clipboard operation
protobuf copied to clipboard

[protoc-gen-go] Variable name clashes in generated code when using `name` or `value` as top-level enum value

Open gustavo-bertoldi opened this issue 2 months ago • 1 comments

What version of protobuf and what language are you using?

  • libprotoc 32.1
  • protoc-gen-go v1.36.9

What did you do?

protoc --go_out=./gen --go_opt=paths=source_relative test.proto

With the following file

syntax = "proto3";

package test;
option go_package = "proto/test";

enum MyEnum {
  unknown = 0;
  name = 1;
  value = 2;
}

What did you expect to see? No name clashes in the internal variables of the generated file

What did you see instead? Variable name clashes:

MyEnum_name redeclared in this block
MyEnum_value redeclared in this block

It seems, for top-level enums, the enum value maps generated for go are named <enum_name>_name and <enum_name>_value. The enum consts have identical names, causing the clash.

Generated code extract:

type MyEnum int32

const (
	MyEnum_unknown MyEnum = 0
	MyEnum_name    MyEnum = 1
	MyEnum_value   MyEnum = 2
)

// Enum value maps for MyEnum.
var (
	MyEnum_name = map[int32]string{
		0: "unknown",
		1: "name",
		2: "value",
	}
	MyEnum_value = map[string]int32{
		"unknown": 0,
		"name":    1,
		"value":   2,
	}
)

A workaround is to wrap the enum inside another message.

gustavo-bertoldi avatar Oct 01 '25 13:10 gustavo-bertoldi

Note that the style guide advises using UPPER_SNAKE_CASE for enum value names: https://protobuf.dev/programming-guides/style/

neild avatar Oct 01 '25 16:10 neild