DEV Community

Rafael Firmino
Rafael Firmino

Posted on • Updated on

Enum in Go ?


Image description

Golang don't have Enumerators!

I show you the simple way for simulate enum in go.

package domain

type Status uint8

const (
    Creating Status = iota

func (s Status) ToString() string{
    switch s {
    case Creating:
        return "Creating"
    case Pending:
        return "Pending"
    case Expired:
        return "Expired"
    case Paid:
        return "Paid"
    case Canceled:
        return "Canceled"
    return "Unknown"
Enter fullscreen mode Exit fullscreen mode


  statusCanceled := Canceled.ToString()

   // in another package
  statusCanceled := domain.Cenceled.ToString()
Enter fullscreen mode Exit fullscreen mode

The tests:

package domain

import (

func TestToString(t *testing.T) {
    type test struct {
        description string
        input       Status
        expected    string

    tests := []test{
        {description: "should return Creating", input: Creating, expected: "Creating"},
        {description: "should return Pending", input: Pending, expected: "Pending"},
        {description: "should return Expired", input: Expired, expected: "Expired"},
        {description: "should return Paid", input: Paid, expected: "Paid"},
        {description: "should return Canceled", input: Canceled, expected: "Canceled"},
        {description: "should return Error", input: Error, expected: "Error"},
        {description: "should return Unknown", input: Unknown, expected: "Unknown"},

    for _, item := range tests {
        t.Run(item.description, func(t *testing.T) {
            assert.Equal(t, item.expected, item.input.ToString())

Enter fullscreen mode Exit fullscreen mode

Top comments (0)