首页 文章

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

提问于
浏览
20

我有以下函数从终端获取命令并根据输入打印一些东西 . 看起来很简单,如果用户键入'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

    }

3 回答

  • 5

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

    在检查 inp[0] == "add" 之前,您可以使用 len(inp) 检查 inp 的长度 . 这样的事情可能会:

    if len(inp) == 0 {
        fmt.Println("you didn't type add")
    } else if inp[0] == "add" {
        fmt.Println("you typed add")
    }
    
  • 20

    你必须首先检查 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
    
    }
    
  • -4

    您也可以使用 recover() 检查切片的现有索引

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

相关问题