3 回答

TA貢獻1859條經(jīng)驗 獲得超6個贊
遍歷天數(shù)數(shù)組以獲取其索引值。檢查傳遞的字符串并獲取匹配字符串索引的值。然后使用該索引獲取第二天的值:
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條經(jīng)驗 獲得超5個贊
你在找什么是枚舉。在 Go 中,它們可以這樣實現(xiàn):
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 底層類型,你可以這樣創(chuàng)建它:
const (
Sunday = "Sunday"
//...
)

TA貢獻1835條經(jīng)驗 獲得超7個贊
您可以枚舉數(shù)組并傳輸數(shù)字和字符串
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 關(guān)注
- 172 瀏覽
添加回答
舉報