DEV Community

Rafael Firmino
Rafael Firmino

Posted on • Edited on

3 2

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay