【问题标题】:How to use enums in go? [duplicate]如何在 go 中使用枚举? [复制]
【发布时间】:2019-05-22 14:25:30
【问题描述】:

在 golang 中是否有简单的枚举实现? 类似以下内容?

type status enum[string] {
    pending = "PENDING"
    active = "ACTIVE"
}

【问题讨论】:

标签: go


【解决方案1】:
const (
    statusPending = "PENDING"
    statusActive  = "ACTIVE"
)

或者,在Ultimate Visual Guide to Go Enums 应用示例

// Declare a new type named status which will unify our enum values
// It has an underlying type of unsigned integer (uint).
type status int

// Declare typed constants each with type of status
const (
    pending status = iota
    active
)

// String returns the string value of the status
func (s status) String() string {
    strings := [...]string{"PENDING", "ACTIVE"}

    // prevent panicking in case of status is out-of-range
    if s < pending || s > active {
        return "Unknown"
    }

    return strings[s]
}

【讨论】:

    【解决方案2】:

    类似以下内容?

    还没有

    阅读这里What is an idiomatic way of representing enums in Go?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 2021-09-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2013-03-29
    相关资源
    最近更新 更多