Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to iterate over constant used as enum

Tags:

I am trying to use enum in golang as below. I am struggling to find a easy way to iterate over the list of constant values. What are common practice in golang to iterate over constant values used as enum. Thanks!

type DayOfWeek int const(        Monday DayOfWeek = iota        Tuesday        Wednesday        Thursday        Friday        Saturday        Sunday       ) 

In Java, we can iterate as below.

public enum DayOfWeek {     MONDAY,      TUESDAY,     WEDNESDAY,     THURSDAY,     FRIDAY,     SATURDAY,     SUNDAY }  for (DayOfWeek day: DayOfWeek.values()) {    // code logic } 
like image 855
Jack_125 Avatar asked Oct 17 '15 16:10

Jack_125


People also ask

Should I use enum for constants?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.

What is better enum or constant?

Enums limit you to the required set of inputs whereas even if you use constant strings you still can use other String not part of your logic. This helps you to not make a mistake, to enter something out of the domain, while entering data and also improves the program readability.

Can we define constants in enum?

The enum type, introduced in Java 5, is a special data type that represents a group of constants. Using enums, we can define and use our constants in the way of type safety. It brings compile-time checking to the constants.

Can you loop through an enum C ++?

C++ Enumeration Iteration over an enumThere is no built-in to iterate over enumeration.

How do you iterate over an enum in a list?

Iterate over Enum Values: There are many ways to iterate over enum values: Iterate Using forEach() Iterate Using for Loop. Iterate Using java.util.stream. Iterate Using forEach(): The forEach() method works on list or set. For using forEach() method, convert enum into list or set.

How to iterate the contents of enum days in Java?

This method returns an array containing all the values. Once you obtain the array you can iterate it using the for loop. Following java program iterates the contents of the enum Days created above, using the for loop −

How to declare an enum in Python?

An enum can contain constants, methods etc. Given below is a demonstration on how to declare an enum: Iterate over Enum Values: There are many ways to iterate over enum values: Iterate Using forEach(): The forEach() method works on list or set. For using forEach() method, convert enum into list or set.

How to convert enum to list or set in Java?

You can convert the enum into a list or set and perform required actions on each element of the list using the forEach () method. Following java program converts the enum Days created above into a set and, iterates its contents using forEach loop − You can use foreach loop with streams too.


2 Answers

There is no direct way to enumerate the values/instances of named type at runtime, whether variables or constants, unless you specifically define a slice that lists them. This is left up to the definer or the user of the enumeration type.

package main  import (     "fmt"     "time" )  var Weekdays = []time.Weekday{     time.Sunday,     time.Monday,     time.Tuesday,     time.Wednesday,     time.Thursday,     time.Friday,     time.Saturday, }  func main() {     for _, day := range Weekdays {             fmt.Println(day)     } } 

In order be able to generate this list dynamically at runtime, e.g. via reflection, the linker would have to retain all the symbols defined in all packages, like Java does. The golang-nuts group discussed this, regarding names and functions exported from a package, a superset of package constant definitions. https://groups.google.com/forum/#!topic/golang-nuts/M0ORoEU115o

It would be possible for the language to include syntactic sugar for generating this list at compile time if and only if it were referenced by the program. What should the iteration order be, though? If your week starts on Monday the list I defined is not very helpful; you will have to define your own slice to range through the days from Monday to Sunday.

like image 53
Jeremy Fishman Avatar answered Sep 28 '22 06:09

Jeremy Fishman


You can do that without reflection.

First execute the Go tools Stringer at compile time using go generate. This creates a file [filename]_string.go which contains a map _[structname]_map of enum values referencing enum variable names as strings. This map is private, so simply assign it to a public map upon package initialization.

var EnumMap map[Enum]string  func init() {     EnumMap = _Enum_map }  type Enum uint  //go:generate go run golang.org/x/tools/cmd/stringer -type=Enum  const (     One Enum = iota     Two ) 

Then you can simply loop over the keys of the map.

like image 37
Victor Deleau Avatar answered Sep 28 '22 07:09

Victor Deleau