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 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?