Go Enumerations: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Tag: Manual revert
 
Line 23: Line 23:
To make the enumeration constants visible outside the package, they need to start with a capital letter.
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:
 
Conversion to and from string representations:
 
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
func (dotw DayOfTheWeek) String() string {
type DayOfTheWeek int
  return []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}[dotw]
 
const (
MON DayOfTheWeek = iota
TUE
WED
THU
FRI
SAT
SUN
)
 
var dayOfTheWeekToString = []string{
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
}
}
</syntaxhighlight>


The inverse conversion can be done with a map:
func (s DayOfTheWeek) String() string {
<syntaxhighlight lang='go'>
return dayOfTheWeekToString[s]
var stringToDayOfTheWeek = map[string]DayOfTheWeek{
"Monday":    MON,
"Tuesday":    TUE,
"Wednesday":  WED,
"Thursday":  THU,
"Friday":    FRI,
"Saturday":  SAT,
"Sunday":    SUN,
}
}


func StringToDayOfTheWeek(s string) DayOfTheWeek {
func StringToDayOfTheWeek(s string) DayOfTheWeek {
c, exists := stringToDayOfTheWeek[s]
for i, v := range dayOfTheWeekToString {
if exists {
if s == v {
return c
return DayOfTheWeek(i)
}
}
}
return DayOfTheWeek(-1)
return DayOfTheWeek(-1)
}
}
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 23:27, 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.


Conversion to and from string representations:

type DayOfTheWeek int

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

var dayOfTheWeekToString = []string{
	"Monday",
	"Tuesday",
	"Wednesday",
	"Thursday",
	"Friday",
	"Saturday",
	"Sunday",
}

func (s DayOfTheWeek) String() string {
	return dayOfTheWeekToString[s]
}

func StringToDayOfTheWeek(s string) DayOfTheWeek {
	for i, v := range dayOfTheWeekToString {
		if s == v {
			return DayOfTheWeek(i)
		}
	}
	return DayOfTheWeek(-1)
}