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

huangapple go评论78阅读模式
英文:

panic: runtime error: index out of range in Go

问题

我有以下函数,它从终端接收一个命令并根据输入打印一些内容。看起来很简单,如果用户输入'add',系统会打印一行,如果用户没有输入任何内容,它会打印其他内容。

每当用户输入add时,它都能正常工作。如果用户没有输入任何内容,它会抛出GoLang中的运行时错误:索引超出范围。

为什么会这样呢?

func bootstrapCmd(c *commander.Command, inp []string) error {
    if inp[0] == "add" {
        fmt.Println("你输入了add")
    } else if inp[0] == "" {
        fmt.Println("你没有输入add")
    }
    return nil
}
英文:

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
    
    }

答案1

得分: 37

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

您可以使用 len(inp) 来检查 inp 的长度,然后再检查 inp[0] == "add"。可以像这样进行检查:

if len(inp) == 0 {
    fmt.Println("您没有输入 add")
} else if inp[0] == "add" {
    fmt.Println("您输入了 add")
}
英文:

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

答案2

得分: 12

你首先需要检查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("你输入了add")
    case "sub":
        fmt.Println("你输入了sub")
    default:
        fmt.Println("无效:", inp[0])
    }
    return nil
}
英文:

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

}

答案3

得分: -7

你可以使用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("你输入了 add")
} else {
    fmt.Println("你没有输入 add")
}

请注意,这只是代码的翻译部分,不包括任何其他内容。

英文:

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

huangapple
  • 本文由 发表于 2014年10月1日 01:01:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/26126235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定