问题描述
我具有以下功能,该功能从终端接收命令并根据输入打印内容.这看起来很简单,如果用户键入"add",则系统将打印一行,如果用户未键入任何内容,则将打印其他内容.
I have the following function that takes a command from terminal and prints something based on input. It seems simple enough, if the user types 'add' the system prints a line, if the user types nothing, it prints something else.
只要用户输入添加,它就起作用.如果用户未输入任何内容,则会抛出
Whenever the user types add, it works. If the user doesn't type anything it throws
紧急:运行时错误:GoLang中的索引超出范围
panic: runtime error: index out of range in 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]
也无法访问.
If the user does not provide any input, the inp
array is empty. This means that even the index 0
is out of range, i.e. inp[0]
can't be accessed.
在检查 inp [0] =="add"
之前,可以使用 len(inp)
检查 inp
的长度.这样的事情可能会做到:
You can check the length of inp
with len(inp)
before checking inp[0] == "add"
. Something like this might do:
if len(inp) == 0 {
fmt.Println("you didn't type add")
} else if inp[0] == "add" {
fmt.Println("you typed add")
}
这篇关于紧急:运行时错误:Go中的索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!