In Go, there isn’t any enum
knowledge kind recognized from languages akin to C++, Java, or Python. Nonetheless, this doesn’t imply that enums
can’t be created. Should you declare constants of customized kind and a few helper strategies, you get a construction similar to enum
in different programming languages.
See the instance under to verify methods to declare enum
in Go.
Within the instance, we use constants declaration with
iota
. Verify our tutorial on methods to useiota
in Go.
package deal principal
import (
"fmt"
)
kind Season int
const (
Spring Season = iota + 1
Summer time
Autumn
Winter
)
func (s Season) String() string {
seasons := [...]string{"spring", "summer time", "autumn", "winter"}
if s < Spring || s > Winter {
return fmt.Sprintf("Season(%d)", int(s))
}
return seasons[s-1]
}
func (s Season) IsValid() bool {
swap s {
case Spring, Summer time, Autumn, Winter:
return true
}
return false
}
func principal() {
mySeasons := []Season{Spring, Summer time, Autumn, Winter, 6}
for _, s := vary mySeasons {
fmt.Printf("season: %s, is legitimate: %tn", s, s.IsValid())
}
}
Output:
season: spring, is legitimate: true
season: summer time, is legitimate: true
season: autumn, is legitimate: true
season: winter, is legitimate: true
season: Season(6), is legitimate: false
The way it works
- Declare customized kind and components of our
enum
kind Season int const ( Spring Season = iota + 1 Summer time Autumn Winter )
As a primary step, we declare new integer kind
Season
and create successive fixed values utilizing theiota
key phrase.Why can we use int kind as an alternative of string?
Constants are often used to check to a variable, e.g.
if Spring != season { // do one thing }
and sometimes we don’t want their particular values, simply the truth that the fixed and the variable are completely different. In such a case evaluating two
int
values is quicker than evaluating two strings. Constants of kindint
additionally take much less reminiscence house.Why can we declare the customized kind
Season
as an alternative of utilizing untyped constants?A customized kind protects in opposition to passing invalid values already on the compilation stage. If we declared seasons as untyped constants, the code under of assigning invalid season worth 6 to the variable would execute with none error:
var d int = 6 season := Spring season = d
When utilizing
Season
kind, to make this code run with none error, it’s essential to explicitly convert thed
variable, so it’s not doable to do it by chance:var d int = 6 season := Spring season = Season(d)
Additionally, a customized kind of
enum
makes the code cleaner. For instance, declaring the performyou instantly see that the perform requires season as an argument, and within the case of
you solely know that it wants an integer argument, with none semantic which means. Due to the customized sorts we can also add strategies to the
enum
components likeString()
andIsValid()
. - Create
String()
methodologyfunc (s Season) String() string { seasons := [...]string{"spring", "summer time", "autumn", "winter"} if s < Spring || s > Winter { return fmt.Sprintf("Season(%d)", int(s)) } return seasons[s-1] }
String()
methodology provides the flexibility to printSeason
constants as astring
moderately than anint
, so for the assertionfmt.Println(Spring)
we getspring
as an alternative of1
. For variables outdoors the varySpring..Winter
, we printSeason(X)
, the placeX
is an integer worth of theSeason
kind variable. - Create
IsValid()
methodologyfunc (s Season) IsValid() bool { swap s { case Spring, Summer time, Autumn, Winter: return true } return false }
IsValid()
is a helper methodology that validates whether or not theSeason
kind variable is without doubt one of the valuesSpring
,Summer time
,Autumn
, orWinter
. This perform ought to all the time be referred to as for consumer enter, to confirm that the consumer has not handed an invalid worth of theenum
. principal()
performfunc principal() { mySeasons := []Season{Spring, Summer time, Autumn, Winter, 6} for _, s := vary mySeasons { fmt.Printf("season: %s, is legitimate: %tn", s, s.IsValid()) } }
The
principal()
perform presents what you get if you use theString()
andIsValid()
strategies for outlined values ofSeason
constants in addition to values out of vary.