英文:
How to prevent/fix panic: runtime error: invalid memory address or nil pointer dereference
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对golang还不熟悉。从下面的代码来看,有时color
可能为nil,但我仍然需要调用GetCategory
函数。这会导致以下错误:
panic: runtime error: invalid memory address or nil pointer dereference
如何优雅地调用GetCategory
函数并避免这个错误?
非常感谢您的帮助!
package main
import (
"fmt"
"strings"
)
type event struct {
color *string
Category *string
}
func GetCategory(color string) (*string, error) {
var category string
if strings.HasPrefix(color, "red") {
category = "likes"
} else if strings.HasPrefix(color, "blue") {
category = "dislikes"
}
return &category, nil
}
func main() {
category := "red"
eventObj := event{
Category: &category,
}
if eventObj.color != nil {
fmt.Println(GetCategory(*eventObj.color))
} else {
fmt.Println("color is nil")
}
}
英文:
I'm new to golang. From the code below, sometimes color
could be nil, but I still need to call GetCategory
. This would result in the err below:
panic: runtime error: invalid memory address or nil pointer dereference
How to call GetCategory
gracefully and avoid the err?
Thanks in advance for any help!
import (
"fmt"
"strings"
)
type event struct {
color *string
Category *string
}
func GetCategory(color string) (*string, error) {
var category string
if strings.HasPrefix(color, "red") {
category = "likes"
} else if strings.HasPrefix(color, "blue") {
category = "dislikes"
}
return &category, nil
}
func main() {
category := "red"
eventObj := event{
Category: &category,
}
fmt.Println(GetCategory(*eventObj.color))
}
</details>
# 答案1
**得分**: 2
如果你需要检查某个东西是否为nil,你只需要*这样做*,然后相应地采取行动。例如:
```go
func GetCategory(color *string) (*string, error) {
if color == nil {
return nil, errors.New("Color is nil")
}
// ...
如果某个东西可能为nil
,你只需在使用之前使用简单的相等或不等检查(== nil
或!= nil
)来检查是否为nil
。
英文:
If you need to check if something is nil, you just do that, and act accordingly. For example:
func GetCategory(color *string) (*string, error) {
if color == nil {
return nil, errors.New("Color is nil")
}
// ...
There is no elvis operator, safe navigation operator, optional chaining etc.
If something might be nil
, you simply check for nil
with a straightforward equality or inequality check (== nil
or != nil
) before you use it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论