枚举

枚举类型

定义

type Weekday int

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

iota

在 Go 中,我们往往通过 iota 来自动地定义枚举值:

const (  // iota is reset to 0
        c0 = iota  // c0 == 0
        c1 = iota  // c1 == 1
        c2 = iota  // c2 == 2
)

const (
        a = 1 << iota  // a == 1 (iota has been reset)
        b = 1 << iota  // b == 2
        c = 1 << iota  // c == 4
)

const (
        u         = iota * 42  // u == 0     (untyped integer constant)
        v float64 = iota * 42  // v == 42.0  (float64 constant)
        w         = iota * 42  // w == 84    (untyped integer constant)
)

const x = iota  // x == 0 (iota has been reset)
const y = iota  // y == 0 (iota has been reset)

const (
        bit0, mask0 = 1 << iota, 1<<iota - 1  // bit0 == 1, mask0 == 0
        bit1, mask1                           // bit1 == 2, mask1 == 1
        _, _                                  // skips iota == 2
        bit3, mask3                           // bit3 == 8, mask3 == 7
)

type Base int

const (
        A Base = iota
        C
        T
        G
)

属性

字符值

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

自定义属性值

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
上一页
下一页