What is an Enum in GoLang?
Overview
This article will teach you about golang enum, iota, and other helper tools. Then we will know about enums in depth, how to use enums without using iota or with iota. We will also see when to use iota and when we should avoid using it.
Introduction
A golang enum (aka enumerator) is a group of related constants together in one type. Golang Enums are a strong feature with many applications. However, compared to the majority of other programming languages, they are implemented very differently in Go. Before knowing about enums, let us explore iota and its uses.
Syntax
What is IOTA?
Golang provides us with a keyword named iota used to implement golang enum. It is a built-in predeclared identifier, that represents successive untyped integer constants. The keyword "iota" stands for an integer constant that starts from zero and auto-increments as more values are added. Once iota has been specified in your constant, it is not necessary for further values.
But the main question is why iota has been introduced. If enums are already doing the same thing what is the need for iota then?
For knowing more about the main reason let's understand this with the help of an example: The below example contains a card that has 4 values:
Another Example:
Problem with this:
What if the list of values you wish to be included in the enum is large? It is not practically possible to manage numbers one by one. This method also has the issue of handling the enum numeric values directly when one or more items are removed. To resolve this problem Golang provides us with the keyword iota keyword.
Now, after Using the iota Keyword:
Another Example:
This code will work exactly similar to the above code but increase the readability and performance of the code.
A practical example of the above demonstration:
Output:
Explanation of the Code:
In the above code, we have a variable that is assigned with integer iota and we simply print the output according to the suit initialization, and in our case, it's Diamond, **that's why it will jump to the case Diamond and prints Suit is Diamond ♢.
Implement Enums using IOTA
- Create a new custom type — Integer Type.
- Declare related constants — Using iota.
- Creating common behaviour — give the type a String function.
- Creating additional behaviour — give the type an EnumIndex function.
In an arithmetic expression, use iota to begin a list of constants at 1 rather than 0.
For Example:
Output:
Explanation of the Code: In the above code, we have four variables North East South and West with iota index starting iota + 1 and in the next, we created an enumindex function which will return us direction according to the main function, and in the main function we are assigning east to the d variable which will print East along with the index 2 in the second line.
Defining Enums as Constants
Example of the Enum as Constants
Output:
Explanation of the Code:
In this code, we are adding variables with integers that are constant throughout the program and can't be changed.
Enum Types
We have two types of enums Numeric enums and String enums, we will both of the examples in the below section.
Adding String Methods to Enum Types
Using the String() function is quite beneficial since it allows you to create printability of a string rather than developing an enum type. It provides more human-readability
Output:
Explanation of the above code
In the above code, we defined season constants with integer values, summer is considered to be our default value 0 if no case is found simply return summer else according to the case the code will run, in our case it is autumn.
Default Enum Values
In the above example of String, we have a season as constant with integer values and we are passing summer as our default value when we are defining our default value we should make sure if it's okay to have a default value that we are defining or not. Else, we have the option to set our default value explicitly, we can add a custom “unknown” or “undefined” value,
For Example, our iota always starts with 0
This can be useful when determining whether or not a value has been set:
We can also skip values if we don't want to add them to the list of constants:
For Example:
Output:
Explanation of the above code
In the above code, we have c1 c3 c4 but not c2 and we put _ which means no value just skip that part. So after skipping, it's giving us 1 3 4, and 2 will be skipped.
Another Example:
Output:
Resetting IOTA
Golang enum has the feature to reset also to the initial value zero by re-declaring iota more than once in the code.
For Example:
Output:
Explanation of the above code
In the above code, we have a different set of const variables in the first we have 0+1000 as our default value, and in the second c1 we are resetting back the iota to 0.Therefore, we get 0 2 1 as our output value.
Using Enums in Practice
Now that you understand how to utilize enums, the next question is when to use them.
Enums can be found throughout the standard library. Some common instances include:
Prefix Flags in the Log Package
Package log is a straightforward logging package. It specifies the Logger type, which includes methods for formatting output. It also contains a predefined standard Logger available through helper methods Print[f|ln], Fatal[f|ln], and Panic[f|ln], which are more convenient to use than manually creating a Logger.
For Example:
Status Codes and Methods in the HTTP Package
HTTP client and server implementations are included in the HTTP package.
Get, Head, Post, and PostForm make HTTP (or HTTPS) requests.
Examples of http packages are:
Standard Grayscale Colours in the Colour Package
Package color implements a basic color library.
For Example:
When not to use IOTA?
In the above section, we saw how to use iota and now we will see when we should avoid using iota, For a list of preset constants, do not use iota. These constants might be HTTP status codes, for example. The code snippet below is NOT acceptable.
For Example:
We should not predefine these HTTP codes at our start.
Why Golang Enums are Needed?
- It keeps programmers aware of using inaccurate values.
- It is used to group constants with similar values.
- It is used to define constants that exhibit similar behavior.
- It improves the readability and maintainability of code.
Points to Remember
- You may use an enum to add default/unknown values and manage them in later implementations.
For Example:
- When creating enum types using iota, certain values can be skipped. There is no value provided for value 2 in the sample enum below.
For Example:
Enums can also be defined as structs instead of as ints or strings.
Conclusion
- This article describes how to implement and use enumerators in the Go programming language.
- Using the String() function is quite beneficial since it allows you to create printability of a string rather than developing an enum type.
- Furthermore, the Enum String Method and the Enum Skip Values were demonstrated with examples.
- We also learned how to reset the "iota" in golang.
- When we should avoid using iota which helps us to know about iota usage.