七叶笔记 » golang编程 » 「Golang系列」可视化图解 Go Enums 和 iota

「Golang系列」可视化图解 Go Enums 和 iota

每天三分钟,知识更轻松。
欢迎关注同名微信公众账号极客24h。 

什么是 enum (枚举)?

枚举将相关常数归为一种类型。

例子

  • 时区: EST, CST…
  • T-shirt 尺码: Small, Medium, Large
  • 服务器状态: Unknown, Running, Stopped, Resumed
  • 我们为什么需要枚举

    • 分组获取内容相关得值
    • 避免使用无效值
    • 提高代码的可读性和可维护性

    Golang 语言中如何创建枚举 。

    例如,假设您要为工作日创建一个枚举。

    每个常量将具有相同的类型:Weekday

    ★ 第一步:声明一个新的自定义类型:Weekday

    type Weekday int 

    ★ 第二步:为Weekday 声明相关常量

    给他们赋予不同数值,以防冲突。

     const  (
      Sunday  Weekday = 0
     Monday Weekday = 1
     Tuesday Weekday = 2
     Wednesday Weekday = 3
     Thursday Weekday = 4
     Friday Weekday = 5
     Saturday Weekday = 6
    )
    fmt.Println(Sunday) // prints 0
    fmt.Println(Saturday) // prints 6 

    为枚举Weekday 创建共同行为

    您将方法附加到类型以定义其行为。

    附加的方法将是Weekday的不可分割的部分,并在Weekday常量之间共享。


    ★ String() method:

    func (day Weekday) String() string {
     // declare an array of strings
     // ... operator counts how many
     // items in the array (7)
     names := [...]string{
     "Sunday", 
     " Monday ", 
     "Tuesday", 
     " Wednesday ",
     " Thursday ", 
     "Friday", 
     "Saturday"}
     // → `day`: It's one of the
     // values of Weekday constants. 
     // If the constant is Sunday,
     // then day is 0.
     //
     // prevent panicking in case of
     // `day` is out of range of Weekday
     if day < Sunday || day > Saturday {
     return "Unknown"
     }
     // return the name of a Weekday
     // constant from the names array 
     // above.
     return names[day]
    } 

    ★ 测试

    fmt.Printf("Which day it is? %s\n", Sunday)
    // Which day it is? Sunday 

    ★ Weekend() method:

    func (day Weekday) Weekend()  bool  {
     switch day {
     case Sunday, Saturday: // If day is a weekend day
     return true
     default: // If day is not a weekend day
     return false
     }
    } 

    ★ 测试

    fmt.Printf("Is Saturday a weekend day? %t\n", Saturday.Weekend())
    // Is Saturday a weekend day? true 

    如何使用iota

    其他常量将重复Iota表达式,直到出现另一个赋值或类型声明。

    我们来试一些小技巧

    除了空行和注释行,iota每行之后都增加1。


    什么时候不用iota

    //server status 
    const (
     RestartMarkerReply = 110
     ServiceReadyInNMinutes = 120
     CommandOK = 200
     CommandNotImplemented = 202
     // ...
    ) 

    这部分会提高你对iota 得理解和认识,具体请看下回。

    相关文章