在Go语言中,如何以惯用方式获取枚举的字符串表示?

4
如果我有一个枚举类型:
type Day int8

const (
    Monday Day = iota
    Tuesday
    ...
    Sunday
)

如何更自然地获取字符串?

函数:

func ToString(day Day) string {
   ...
}

或者方法
func (day Day) String() string  {
    ... 
}

1
看看这个:https://blog.golang.org/generate 对于你的使用情况可能更合适。 - ssemilla
可能是在Go中表示枚举的惯用方式是什么?的重复问题。 - Jonathan Hall
3个回答

11

第二个更加通俗易懂,因为它满足Stringer接口。

func (day Day) String() string  {
    ... 
}

我们将此方法声明在Day类型上,而不是*Day类型上,因为我们不改变值。

这将使您能够编写。

fmt.Println(day)

并获取由String方法产生的值。


谢谢,Grzegorz Żur。我会遵循这种方式。但是还有另一种观点:如果我们不改变类型状态-最好声明函数。 - Sergii Getman
@SergiiGetman能否更好地解释一下“我们不改变类型状态”的部分? - Grzegorz Żur
Grzegorz Żur。我是Go的新手,可能会有错误。但是我的想法是,如果我们有一个类型,例如struct,并且我们有一些改变该结构的代码片段,最好将其作为该类型的方法。如果我们只是使用该类型,我们可以创建函数。 - Sergii Getman

7

你自己回答这个问题的简单方法是查看Go标准库。


Package time

import "time" 

type Weekday

A Weekday specifies a day of the week (Sunday = 0, ...).

type Weekday int

const (
        Sunday Weekday = iota
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
        Saturday
)

func (Weekday) String

func (d Weekday) String() string

String returns the English name of the day ("Sunday", "Monday", ...).

src/time/time.go:

// A Weekday specifies a day of the week (Sunday = 0, ...).

type Weekday int

const (
    Sunday Weekday = iota
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
)

var days = [...]string{
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
}

// String returns the English name of the day ("Sunday", "Monday", ...).
func (d Weekday) String() string {
    if Sunday <= d && d <= Saturday {
        return days[d]
    }
    buf := make([]byte, 20)
    n := fmtInt(buf, uint64(d))
    return "%!Weekday(" + string(buf[n:]) + ")"
}

Package fmt

import "fmt" 

type Stringer

Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.

type Stringer interface {
        String() string
}

0
也许我的答案会有一定的性能损失,但是当处理大量枚举时,使用映射将是一个可怕的想法。 类别类型字符串。
type Category string

const (
    AllStocks        Category = "all"
    WatchList        Category = "watch_list"
    TopGainer        Category = "top_gainer_stock"
    TopLoser         Category = "top_loser_stock"
    FiftyTwoWeekHigh Category = "high_stocks"
    FiftyTwoWeekLow  Category = "low_stocks"
    HotStocks        Category = "hot_stock"
    MostTraded       Category = "most_active_stock"
)

func (c Category) toString() string {
    return fmt.Sprintf("%s", c)
}

这是枚举值最简单的字符串格式化方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接