Skip to content

Commit d21b2ed

Browse files
Adds guidance on prefixing enum values in proto2 and proto3.
PiperOrigin-RevId: 839751775
1 parent c532b8b commit d21b2ed

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

content/programming-guides/proto2.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,30 @@ message SearchRequest {
745745
}
746746
```
747747

748+
### Prefixing Enum Values {#prefixing-values}
749+
750+
When prefixing enum values, the remainder of the name with the prefix stripped
751+
should still be a legal and style-conformant enum name. For example, avoid the
752+
following:
753+
754+
```proto
755+
enum DeviceTier {
756+
DEVICE_TIER_UNKNOWN = 0;
757+
DEVICE_TIER_1 = 1;
758+
DEVICE_TIER_2 = 2;
759+
}
760+
```
761+
762+
Instead, use a value name like `DEVICE_TIER_TIER1`, where the `DEVICE_TIER_`
763+
portion is viewed as scoping the enum value rather than as part of the
764+
individual enum value name. Some Protobuf implementations automatically strip
765+
the prefix that matches the containing enum name where it is safe to do so, but
766+
could not in this example since a bare `1` is not a legal enum value name.
767+
768+
We plan for a future Edition to add support for scoped enums, which will
769+
eliminate the need to manually prefix each enum value and enable this to be
770+
written succinctly as `TIER1 = 1`.
771+
748772
### Enum Default Value {#enum-default}
749773

750774
The default value for the `SearchRequest.corpus` field is `CORPUS_UNSPECIFIED`

content/programming-guides/proto3.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,30 @@ message SearchRequest {
739739
}
740740
```
741741

742+
### Prefixing Enum Values {#prefixing-values}
743+
744+
When prefixing enum values, the remainder of the name with the prefix stripped
745+
should still be a legal and style-conformant enum name. For example, avoid the
746+
following:
747+
748+
```proto
749+
enum DeviceTier {
750+
DEVICE_TIER_UNKNOWN = 0;
751+
DEVICE_TIER_1 = 1;
752+
DEVICE_TIER_2 = 2;
753+
}
754+
```
755+
756+
Instead, use a value name like `DEVICE_TIER_TIER1`, where the `DEVICE_TIER_`
757+
portion is viewed as scoping the enum value rather than as part of the
758+
individual enum value name. Some Protobuf implementations automatically strip
759+
the prefix that matches the containing enum name where it is safe to do so, but
760+
could not in this example since a bare `1` is not a legal enum value name.
761+
762+
We plan for a future Edition to add support for scoped enums, which will
763+
eliminate the need to manually prefix each enum value and enable this to be
764+
written succinctly as `TIER1 = 1`.
765+
742766
### Enum Default Value {#enum-default}
743767

744768
The default value for the `SearchRequest.corpus` field is `CORPUS_UNSPECIFIED`

0 commit comments

Comments
 (0)