3 回答
TA贡献1859条经验 获得超6个赞
遍历天数数组以获取其索引值。检查传递的字符串并获取匹配字符串索引的值。然后使用该索引获取第二天的值:
package main
import (
"fmt"
)
var (
counter int
day string
)
func main() {
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(&day)
for key, value := range dag {
if day == value {
counter = key
}
}
fmt.Println(counter)
if counter == 6 {
counter = 0
fmt.Println(dag[counter])
}
if counter != 6 {
counter = counter + 1
fmt.Println(dag[counter])
}
}
或者正如 Peter 所建议的那样,您也可以使用地图,在这种情况下更方便和易于使用:
package main
import (
"fmt"
)
func main() {
var value string
dag := make(map[string]string)
dag["Zondag"] = "Maandag"
dag["Maandag"] = "Dinsdag"
dag["Dinsdag"] = "Woensdag"
dag["Woensdag"] = "Donderdag"
dag["Donderdag"] = "Vrijdag"
dag["Vrijdag"] = "Zaterdag"
fmt.Println("Welke dag is het?")
fmt.Scan(&value)
fmt.Println(dag[value])
}
Go Playground上的工作代码
TA贡献1866条经验 获得超5个赞
你在找什么是枚举。在 Go 中,它们可以这样实现:
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)
如果你不需要 int 底层类型,你可以这样创建它:
const (
Sunday = "Sunday"
//...
)
TA贡献1835条经验 获得超7个赞
您可以枚举数组并传输数字和字符串
func GetNextDay(someday string){
for i, v := range dag{
if v == someday {
if i==6 {
i = 0
}else {
i = i + 1
}
return dag[i]
}
}
return "no such day in a week"
}
- 3 回答
- 0 关注
- 119 浏览
添加回答
举报