我有以下函数从终端获取命令并根据输入打印一些东西。看起来很简单,如果用户键入’add’,系统会打印一行,如果用户没有输入任何内容,则会输出其他内容。
每当用户键入add时,它都有效。如果用户没有输入它抛出的任何内容
panic:运行时错误:GoLang中的索引超出范围
为什么是这样?
func bootstrapCmd(c *commander.Command, inp []string) error {
if inp[0] == "add" {
fmt.Println("you typed add")
} else if inp[0] == "" {
fmt.Println("you didn't type add")
}
return nil
}
解决办法:
如果用户未提供任何输入,则该inp数组为空。这意味着即使索引0超出范围,即inp[0]无法访问。
您可以在检查之前检查inpwith 的长度。这样的事情可能会:len(inp)inp[0] == “add”
if len(inp) == 0 {
fmt.Println("you didn't type add")
} else if inp[0] == "add" {
fmt.Println("you typed add")
}
你必须检查第一个长度inp:
func bootstrapCmd(c *commander.Command, inp []string) (err error) {
if len(inp) == 0 {
return errors.New("no input")
}
switch inp[0] {
case "add":
fmt.Println("you typed add")
case "sub":
fmt.Println("you typed sub")
default:
fmt.Println("invalid:", inp[0])
}
return nil
}