What is the usage of the ‘go’ keyword?

In Go language, enumeration can be achieved by defining constant groups using the const keyword. Even though Go language does not have an enum type, the same effect can be accomplished by using constant groups.

Here is an example code using a constant group to implement an enumeration:

package main

import "fmt"

const (
    Sunday    = iota // 0
    Monday           // 1
    Tuesday          // 2
    Wednesday        // 3
    Thursday         // 4
    Friday           // 5
    Saturday         // 6
)

func main() {
    day := Monday

    switch day {
    case Sunday:
        fmt.Println("Sunday")
    case Monday:
        fmt.Println("Monday")
    case Tuesday:
        fmt.Println("Tuesday")
    case Wednesday:
        fmt.Println("Wednesday")
    case Thursday:
        fmt.Println("Thursday")
    case Friday:
        fmt.Println("Friday")
    case Saturday:
        fmt.Println("Saturday")
    }
}

In the code above, we defined a group of constants using the const keyword, and each constant is assigned an incremented value using iota to mimic an enumeration. We then used a switch statement in the main function to output the corresponding day of the week based on the enum value.

Overall, Go language does not have a native enumeration type, but the effect of enumeration can be achieved through constant groups.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds