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
panic: runtime error: index out of range in GoLang
Why is this?
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 }
Runtime error list index out of bounds – This problem can sometimes appear because the application you're trying to run isn't fully compatible with Windows 10. To fix that, just run the application in Compatibility mode and check if that helps.
Generally, list index out of range means means that you are providing an index for which a list element does not exist.
Recover is a function provided by Go which takes control of a panicking goroutine. recover() can only be used inside deferred functions. If you call recover() during normal flow, it will simply return nil . However, if a goroutine is panicking, recover() will capture the panic value.
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.
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") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With