Go Enumerations: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 27: Line 27:
func (dotw DayOfTheWeek) String() string {
func (dotw DayOfTheWeek) String() string {
   return []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}[dotw]
   return []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}[dotw]
}
</syntaxhighlight>
The inverse conversion can be done with a map:
<syntaxhighlight lang='go'>
var stringToDayOfTheWeek = map[string]DayOfTheWeek{
"Monday":    MON,
"Tuesday":    TUE,
"Wednesday":  WED,
"Thursday":  THU,
"Friday":    FRI,
"Saturday":  SAT,
"Sunday":    SUN,
}
func StringToDayOfTheWeek(s string) DayOfTheWeek {
c, exists := stringToDayOfTheWeek[s]
if exists {
return c
}
return -1
}
}
</syntaxhighlight>
</syntaxhighlight>

Revision as of 23:13, 11 March 2024

External

Internal

Overview

Go does not have formal enums, but the language allows for sets of related, yet distinct int constants. They represent a property that has several distinct possible int values, like the days of the weeks or the months of the year. They are declared using the pre-declared constant iota:

type DayOfTheWeek int
const (
  MON DayOfTheWeek = iota
  TUE
  WED
  THU
  FRI
  SAT
  SUN
)

To make the enumeration constants visible outside the package, they need to start with a capital letter.

The enumeration constants can be rendered as strings by making the enum type implement a Stringer interface:

func (dotw DayOfTheWeek) String() string {
  return []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}[dotw]
}

The inverse conversion can be done with a map:

var stringToDayOfTheWeek = map[string]DayOfTheWeek{
	"Monday":     MON,
	"Tuesday":    TUE,
	"Wednesday":  WED,
	"Thursday":   THU,
	"Friday":     FRI,
	"Saturday":   SAT,
	"Sunday":     SUN,
}
func StringToDayOfTheWeek(s string) DayOfTheWeek {
	c, exists := stringToDayOfTheWeek[s]
	if exists {
		return c
	}
	return -1
}