在使用json包解码指针值后,我需要添加nil检查吗?

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

Do I need to add nil check after decoding a pointer value with the json package?

问题

我已经长时间使用Go语言进行编程,最近在重写代码时遇到了一个奇怪的问题。我进行了几次测试,发现if request == nil的检查从未生效。以前,我总是担心会出现nil指针异常,所以在各个地方都插入了检查。但在这种情况下,json解码错误处理程序似乎覆盖了所有情况。

	var (
		request *models.Owner
		err     error
	)

	err = json.NewDecoder(r.Body).Decode(&request)
	if err != nil {
		render.Render(w, r, response.ErrInvalidRequest(err))
		return
	}

	if request == nil {
		render.Render(w, r, response.ErrInvalidRequest("request is nil"))
		return
	}

if request == nil这个检查是必要的吗?也许这个检查是多余的,如果我在项目中删除这个检查,代码会变得更清晰。

英文:

I have been writing in Go for a long time and recently while rewriting the code I came across a strange thing. I did a couple of tests and if request == nil check never worked. Previously, I was always afraid of getting a nil pointer exception, and so I inserted checks everywhere. But in this case, the json decode error handler seems to cover all cases.

	var (
		request *models.Owner
		err     error
	)

	err = json.NewDecoder(r.Body).Decode(&request)
	if err != nil {
		render.Render(w, r, response.ErrInvalidRequest(err))
		return
	}

	if request == nil {
		render.Render(w, r, response.ErrInvalidRequest("request is nil"))
		return
	}

if request == nil is it possible to catch this? Perhaps this check is unnecessary, and if I remove this check in my project, the code will become cleaner.

答案1

得分: 0

可能会返回nil错误,并且request仍然为nil,但只有当输入的JSON是JSON的null值时才会出现这种情况。

例如:

type Owners struct {
	Name string
}

var request *Owners

if err := json.Unmarshal([]byte("null"), &request); err != nil {
	panic(err)
}

fmt.Println(request == nil)
fmt.Println(request)

这将输出(在Go Playground上尝试):

true
<nil>

这在json.Unmarshal()中有记录:

为了将JSON解组为指针,Unmarshal首先处理JSON为JSON字面值null的情况。在这种情况下,Unmarshal将指针设置为nil。 否则,Unmarshal将JSON解组为指针指向的值。如果指针为nil,则Unmarshal为其分配一个新值。

英文:

It is possible that nil error will be returned and request will still be nil, but only if the input JSON is the JSON null value.

For example:

type Owners struct {
	Name string
}

var request *Owners

if err := json.Unmarshal([]byte(&quot;null&quot;), &amp;request); err != nil {
	panic(err)
}

fmt.Println(request == nil)
fmt.Println(request)

This will output (try it on the Go Playground):

true
&lt;nil&gt;

This is documented at json.Unmarshal():

> To unmarshal JSON into a pointer, Unmarshal first handles the case of the JSON being the JSON literal null. In that case, Unmarshal sets the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates a new value for it to point to.

huangapple
  • 本文由 发表于 2021年10月19日 18:01:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/69628830.html
匿名

发表评论

匿名网友

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

确定