Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

panic: runtime error: index out of range in Go

Tags:

go

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      } 
like image 828
sourcey Avatar asked Sep 30 '14 17:09

sourcey


People also ask

How do I fix runtime error index out of bounds?

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.

What does it mean when it says Index was out of range?

Generally, list index out of range means means that you are providing an index for which a list element does not exist.

How do you catch panic in Golang?

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.


1 Answers

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") } 
like image 196
aioobe Avatar answered Sep 21 '22 19:09

aioobe