Sobes.tech
Senior

Why is it better to make status an enum, and when is it better to use a string?

sobes.tech AI

Answer from AI

Using enums for statuses is preferable when the set of possible values is fixed and known in advance. This allows:

  • To avoid errors due to typos, as the compiler checks the values.
  • To improve code readability and maintainability.
  • To facilitate refactoring.

In Go, enums are usually implemented through a type based on int with iota constants:

type Status int

const (
    StatusPending Status = iota
    StatusActive
    StatusInactive
)

Using strings is better when:

  • The set of statuses may expand dynamically or change frequently.
  • Convenient logging and interaction with external systems are required (e.g., JSON API), where strings are more visual.

In this case, string constants can be used:

const (
    StatusPending  = "pending"
    StatusActive   = "active"
    StatusInactive = "inactive"
)

Summary: enums are better for fixed, limited sets, while strings offer flexibility and ease of integration.