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 java 判断某个数 区间是否存在
  • ¥15 appium控制多个雷电模拟器问题
  • ¥15 C# iMobileDevice
  • ¥15 谁会做这个啊#ensp#Boson NetSim
  • ¥15 如何编写针对TPS6503320FRGE型号的电源管理芯片的编程代码?
  • ¥15 设计简单目录管理系统,要满足以下内容
  • ¥15 关于九十度混合耦合器信号分析问题
  • ¥15 Cesm如何关闭不用的模块呢
  • ¥15 vue2两层数据导出为excle
  • ¥15 有人能帮我做一下这个项目吗