Friday, March 29, 2024
HomeGolangDeclare enum in Go (Golang)

Declare enum in Go (Golang)



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 use iota 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

  1. 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 the iota 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 kind int 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 the d 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 perform

    you 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 like String() and IsValid().

  2. Create String() methodology
    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]
    }
    

    String() methodology provides the flexibility to print Season constants as a string moderately than an int, so for the assertion fmt.Println(Spring) we get spring as an alternative of 1. For variables outdoors the vary Spring..Winter, we print Season(X), the place X is an integer worth of the Season kind variable.

  3. Create IsValid() methodology
    func (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 the Season kind variable is without doubt one of the values Spring, Summer time, Autumn, or Winter. 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 the enum.

  4. principal() perform
    func 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 the String() and IsValid() strategies for outlined values of Season constants in addition to values out of vary.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments