英文:
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("null"), &request); err != nil {
panic(err)
}
fmt.Println(request == nil)
fmt.Println(request)
This will output (try it on the Go Playground):
true
<nil>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论