panic: runtime error: index out of range in Go

前端 未结 3 1193
耶瑟儿~
耶瑟儿~ 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:19

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

提交回复
热议问题