How to create an enumeration of constants with and without explicit values in Go

1 Answer

0 votes
/* 
   Title: Enumeration of Constants in Go
   Example with and without explicit values (using iota)
*/

package main

import "fmt"

// Enum WITHOUT explicit values (iota starts at 0)
const (
    Red = iota   // 0
    Green        // 1
    Blue         // 2
)

// Enum WITH explicit and mixed values
const (
    OK = 1       // 1
    Warning = 5  // 5
    Error        // 6 (auto: previous + 1)
    Critical = 10 // 10
)

func main() {
    fmt.Println("Enum without explicit values:")
    fmt.Println("Red =", Red)
    fmt.Println("Green =", Green)
    fmt.Println("Blue =", Blue)

    fmt.Println("\nEnum with explicit and mixed values:")
    fmt.Println("OK =", OK)
    fmt.Println("Warning =", Warning)
    fmt.Println("Error =", Error)
    fmt.Println("Critical =", Critical)
}


/* 
run:

Enum without explicit values:
Red = 0
Green = 1
Blue = 2

Enum with explicit and mixed values:
OK = 1
Warning = 5
Error = 6
Critical = 10

*/

 



answered Apr 25 by avibootz

Related questions

...