| Permalink

Go Package Design Tips : Custom Type Enums

When writing a Go package that abstracts some known domain, you might come across the situation of having to deal with predefined values that call for using enums.

Go doesn’t have enums, so the idiomatic way would be to use constants (iota, optionally). For example, one could define the different statuses of something in the following way:

1
2
3
4
5
6
7
8
9
const (
	StatusPending  = "pending"
	StatusActive   = "active"
	StatusInactive = "inactive"
)

type Something struct {
	Status string
}

While this works generally fine and its not a bad solution, what I usually prefer is to rely on custom type definitions, like the example below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type SomethingStatus = string

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

type Something struct {
	Status SomethingStatus
}

I believe this way, the code becomes a more expressive and more flexible, especially considering the perks of defining your own types.

Followed Articles

Status update, February 2021

Hi! Once again my focus has been Wayland-related projects this month. A steady stream of improvements made it into wlroots: Xyene…

via emersion February 22, 2021
Generated by openring