dtyrxmoj20617 2018-09-12 00:37
浏览 35
已采纳

在golang中显示一周的第二天

I've just started my study IT and I thought it would be fun to make a little program that would show you what day it is tomorrow. Sadly I'm stuck. Currently it's working when you write the correct number from the array, but I would like it to work with a string. So when you write 'Maandag' (monday in Dutch), the program will answer Dinsdag (Tuesday in Dutch)

This is my code so far:

package main

import (
    "fmt"
)

func main() {

    var counter int

    var dag [7]string
    dag[0] = "Zondag"
    dag[1] = "Maandag"
    dag[2] = "Dinsdag"
    dag[3] = "Woensdag"
    dag[4] = "Donderdag"
    dag[5] = "Vrijdag"
    dag[6] = "Zaterdag"

    fmt.Println("Welke dag is het?")
    fmt.Scan(&counter)

    if counter == 6 {
        counter = 0
        fmt.Println(dag[counter])
    }

    if counter != 6 {
        counter++
        fmt.Println(dag[counter])
    }
}

展开全部

  • 写回答

3条回答 默认 最新

  • dpf7891 2018-09-12 01:02
    关注

    What are you looking for are enums. In Go they can be implemented like this:

    type Weekday int 
    
    const (
       Sunday    Weekday = iota
       Monday    
       Tuesday   
       Wednesday 
       Thursday  
       Friday    
       Saturday   
    )
    
    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]
    }
    
    // will display "Sunday"
    fmt.Println(Sunday)
    
    // will display "Monday"
    fmt.Println(Sunday + 1)
    

    If you do not need int underlying type, you can create it like this:

    const (
        Sunday = "Sunday"
         //...
    )
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部