Go의 열거형?

7763 단어 go


Golang에는 열거자가 없습니다!

enum을 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"
}


사용:

  statusCanceled := Canceled.ToString()

   // in another package
  statusCanceled := domain.Cenceled.ToString()


테스트:

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())
        })
    }
}

좋은 웹페이지 즐겨찾기