英文:
Golang handling nil pointer exceptions
问题
考虑以下代码:
list := strings.Split(somestring, "\n")
假设这返回一个包含三个元素的列表或切片。然后,如果你尝试访问切片范围之外的元素:
someFunction(list[3])
程序可能因为空指针而崩溃。在Golang中,有没有一种处理空指针异常的方法,以防止程序崩溃,并能适当地做出响应?
英文:
Consider the following code:
list := strings.Split(somestring, "\n")
Let's say this returns a list or slice of three elements. Then, if you try to access something outside the range of the slice:
someFunction(list[3])
The program can crash because of a nil pointer. Is there some way in Golang to handle a nil pointer exception so that the program won't crash and can instead respond appropriately?
答案1
得分: 14
你不能在Go语言中这样做,即使你可以也不应该这样做。
每次你尝试在切片或数组上使用未经检查的索引时,上帝就会杀死一只小猫,所以请始终检查你的变量和切片。我喜欢小猫,所以我对此很在意。
解决这个问题非常简单,可以参考以下示例代码:
func getItem(l []string, i int) (s string) {
if i < len(l) {
s = l[i]
}
return
}
func main() {
sl := []string{"a", "b"}
fmt.Println(getItem(sl, 1))
fmt.Println(getItem(sl, 3))
}
你可以在这个示例链接中查看代码运行结果。
英文:
You can't do that in Go, and you shouldn't even if you can.
Always check your variables and slices, God kills a kitten every time you try to use an unchecked index on a slice or an array, I like kittens so I take it personally.
It's very simple to work around it, example:
func getItem(l []string, i int) (s string) {
if i < len(l) {
s = l[i]
}
return
}
func main() {
sl := []string{"a", "b"}
fmt.Println(getItem(sl, 1))
fmt.Println(getItem(sl, 3))
}
答案2
得分: 1
Go语言中有panic和recover语句,它们的工作方式类似于Java或C#中的异常。
访问空指针会引发panic,如果你不使用recover来捕获它,应用程序将崩溃。
但是Go语言不鼓励使用panic/recover来处理这些异常,你应该在使用指针之前检查它是否为nil。
参考链接:http://blog.golang.org/defer-panic-and-recover
英文:
Go has panic recover statements it works like exception in java or c#
see http://blog.golang.org/defer-panic-and-recover
Access nil pointer will cause a panic, and if you don't use recover to catch it the app will crash.
But go doesn't encourage use panic/recover to handle those exceptions, you probably should check if a pointer is nil before use it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论