dtyrxmoj20617 2018-09-12 08: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 09: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条)

报告相同问题?

悬赏问题

  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决