如何预防/修复 panic: runtime error: invalid memory address or nil pointer dereference。

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

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

没有Elvis运算符安全导航运算符可选链式调用等。

如果某个东西可能为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(&quot;Color is nil&quot;)
  }
  // ...

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.

huangapple
  • 本文由 发表于 2021年11月18日 00:03:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/70007766.html
匿名

发表评论

匿名网友

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

确定