使用 json 包解码指针值后是否需要添加 nil 检查?

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这个能抓到吗?也许这个检查是不必要的,如果我在我的项目中删除这个检查,代码会变得更干净。

可能会返回 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():

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.