dtsjq28482
2018-10-23 08:43
浏览 300
已采纳

在Go中获取枚举的字符串表示形式的惯用方式是什么?

If I have an enum:

type Day int8

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

What is more natural Go way to get string of it?

fucntion:

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

or method

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

图片转代码服务由CSDN问答提供 功能建议

如果我有枚举:

  type Day int8 \  n 
const(
星期一= iota 
星期二
 ... 
星期日
)
   
 
 

更自然的是 Go 获取字符串的方法吗?

功能:

  func ToString(day Day) 字符串{
 ... 
} 
   
 
 

或方法

  func(天天)String(  )字符串{
 ... 
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dragon8899 2018-10-23 08:46
    已采纳

    The second one is more idiomatic because it satisfies Stringer interface.

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

    We declare this method on the Day type not *Day type because we are not changing the value.

    It will enable you to write.

    fmt.Println(day)
    

    and get the value produced by String method.

    打赏 评论
  • dongliyan9190 2018-10-23 10:01

    The easy way for you to answer this question yourself is to look at the Go standard library.


    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
    }
    
    打赏 评论

相关推荐 更多相似问题