Implementing Enum Values in Go

The Go language does not provide an enum definition, but we can use const to simulate enum types, which is a conventional practice in Go.

For example, in the Kubernetes project, there are numerous “enum values” defined in the form of constants:

  1. // PodPhase is a label for the condition of a pod at the current time.
  2. type PodPhase string
  3. // These are the valid statuses of pods.
  4. const (
  5. // PodPending means the pod has been accepted by the system, but one or more of the containers
  6. // has not been started. This includes time before being bound to a node, as well as time spent
  7. // pulling images onto the host.
  8. PodPending PodPhase = "Pending"
  9. // PodRunning means the pod has been bound to a node and all of the containers have been started.
  10. // At least one container is still running or is in the process of being restarted.
  11. PodRunning PodPhase = "Running"
  12. // PodSucceeded means that all containers in the pod have voluntarily terminated
  13. // with a container exit code of 0, and the system is not going to restart any of these containers.
  14. PodSucceeded PodPhase = "Succeeded"
  15. // PodFailed means that all containers in the pod have terminated, and at least one container has
  16. // terminated in a failure (exited with a non-zero exit code or was stopped by the system).
  17. PodFailed PodPhase = "Failed"
  18. // PodUnknown means that for some reason the state of the pod could not be obtained, typically due
  19. // to an error in communicating with the host of the pod.
  20. PodUnknown PodPhase = "Unknown"
  21. )

How to Efficiently Maintain Enum Values Across Services

It is relatively simple to use enum values internally within a project, as they can be defined and used internally. However, when it comes to cross-service calls or front-end and back-end collaboration, efficiency tends to be lower. When services need to demonstrate interface capabilities to external callers, an API interface document (or interface definition file, such as proto) often needs to be generated, and the client SDK for calling is often generated based on the interface document (file).

If it’s an interface definition file, like proto, the problem can often be resolved by directly viewing the source code, so it’s not a big issue. Here, we mainly discuss the problem of maintaining enum values in interface documents, particularly when maintaining enum values through the OpenAPI standard protocol during front-end and back-end collaboration. We provide specialized tools for maintaining these enum values, please refer to the chapter: Enums Maintenance