恐慌:运行时错误:Go中的索引超出范围

sou*_*cey 24 go

我有以下函数从终端获取命令并根据输入打印一些东西.看起来很简单,如果用户键入'add',系统会打印一行,如果用户没有输入任何内容,则会打印其他内容.

每当用户输入添加时,它都有效.如果用户没有输入它抛出的任何内容

恐慌:运行时错误: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

    }
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 24

如果用户未提供任何输入,则该inp数组为空.这意味着即使索引0超出范围,也就是inp[0]无法访问.

您可以检查的长度inplen(inp)前检查inp[0] == "add".这样的事情可能会:

if len(inp) == 0 {
    fmt.Println("you didn't type add")
} else if inp[0] == "add" {
    fmt.Println("you typed add")
}
Run Code Online (Sandbox Code Playgroud)


One*_*One 5

你必须检查第一个长度inp:

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

}
Run Code Online (Sandbox Code Playgroud)