panic: runtime error: index out of range in Go

前端 未结 3 1191
耶瑟儿~
耶瑟儿~ 2021-02-07 00:01

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,

3条回答
  •  野性不改
    2021-02-07 00:26

    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
    
    }
    

提交回复
热议问题