DEV Community

Rafael Firmino
Rafael Firmino

Posted on • Updated on

Enum in Go ?

#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
    Pending
    Expired
    Paid
    Canceled
    Error
    Unknown
)

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

Using:

  statusCanceled := Canceled.ToString()

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

The tests:

package domain

import (
    "github.com/stretchr/testify/assert"
    "testing"
)

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)