所以我正在開始一個我想做一段時間的項目,我要做的第一件事就是打印一個菜單,我想知道是否有更好/更好的方法來編碼這段代碼。為了“美化”它,我稱之為我正在考慮做這樣的事情fmt.Println("You have chosen option " + input)但是我必須為選擇的每個選項調用不同的命名函數,所以我不確定如何使它工作func main() { fmt.Println("Hello welcome") var input int fmt.Println("Please choose an option:") fmt.Scanln(&input) if input == 1 { fmt.Println("Option 1 chosen") } else if input == 2 { fmt.Println("Option 2 chosen") } else if input == 3 { fmt.Println("Option 3 chosen") } else if input == 4 { fmt.Println("Option 4 chosen") } else if input == 5 { fmt.Println("Option 5 chosen") } else if input == 6 { fmt.Println("Option 6 chosen") } else if input == 7 { fmt.Println("Option 7 chosen") } else if input == 8 { fmt.Println("Option 8 chosen") } else if input == 9 { fmt.Println("Option 9 chosen") } else if input == 10 { fmt.Println("Option 10 chosen") } else { fmt.Print("Not an option") }}
1 回答

互換的青春
TA貢獻1797條經驗 獲得超6個贊
我建議制作一個函數的選項編號映射,如下所示:
func func1() {
fmt.Print("Option 1 Chosen")
}
func func2() {
fmt.Print("Option 2 Chosen")
}
func main() {
funcs := map[int]func() {
1: func1,
2: func2,
}
fmt.Println("Hello welcome")
var input int
fmt.Println("Please choose an option:")
fmt.Scanln(&input)
f, ok := funcs[input]
if !ok {
fmt.Print("Not an option")
} else {
f()
}
}
- 1 回答
- 0 關注
- 83 瀏覽
添加回答
舉報
0/150
提交
取消