sourcey
sourcey

Reputation: 2691

panic: runtime error: index out of range in 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

    }

Upvotes: 38

Views: 115982

Answers (3)

theaidem
theaidem

Reputation: 217

Also you can use recover() for check existing index of slices

func takes(s []string, i int) string {
    defer func() {
        if err := recover(); err != nil {
           return
        }
    }()
    return s[i]
}

if takes(inp,0) == "add" {
   fmt.Println("you typed add")
} else {
   fmt.Println("you didn't type add")
}

Upvotes: -7

aioobe
aioobe

Reputation: 420951

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")
}

Upvotes: 38

OneOfOne
OneOfOne

Reputation: 99225

You have to check the length of inp first:

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

}

Upvotes: 13

Related Questions