Analogue for C++ Enum in Golang

I rewrite some C++ code, but could not find an elegant solution. For example:

#include <iostream>

enum color
{
    red,
    yellow,
    green,
    blue
};
 
std::ostream& operator<<(std::ostream& os, color c)
{
    switch(c)
    {
        case red   : os << "red";    break;
        case yellow: os << "yellow"; break;
        case green : os << "green";  break;
        case blue  : os << "blue";   break;
        default    : os.setstate(std::ios_base::failbit);
    }
    return os;
}
 
int main()
{
    color col = red;
    std::cout << "col = " << col <<std::endl;
}

What corresponds to Go enum from C++?

you can use iota.

package main

const (
        a = iota 
        b = iota
        c = iota
)

func main () {
	println (a, b, c)
}

That would be Iota.

as far as I understood iota allows create a number of constant variables with a sequence value. But enum in C++ has another purpose: to create an object from a bounded domain values. this is the aspect that interests me. I’m sorry that is not clearly formulated idea originally.

Turn out you can make iota work like this.

(edit: copy-paste code in link, in case it does not work)

package main

import "fmt"

type Color int

const (
    red Color = iota
    yellow
    green
    blue
)

func (c *Color) Name() string {
    switch *c {
    case red:
        return "red"
    case yellow:
        return "yellow"
    case green:
        return "green"
    case blue:
        return "blue"
    }
    return ""
}

func main() {
    col := red
    fmt.Println("col = ", col.Name())
}
2 Likes

Thank you, what was needed. I forgot that in Go alias type is a new type.

You can also use the go:generate with the stringer command, like this article from the go blog. Then you don’t even need to write the function!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.