为什么json.Unmarshal使用引用而不是指针? [英] Why does json.Unmarshal work with reference but not pointer?

查看:3172
本文介绍了为什么json.Unmarshal使用引用而不是指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个例子来自 json.Unmarshal 文档(为简单起见稍作修改以使用动物而不是 []动物)的作品,没有错误:

工作示例的游乐场链接

  // ... 
var animals动物
err:= json.Unmarshal(jsonBlob,& animals)
// ...

但是这个稍作修改的例子不会:

非工作示例的播放链接

  // //。 .. 
var animals * Animal
err:= json.Unmarshal(jsonBlob,animals)
// ...

它显示了一个真正无用的错误错误(看起来更像是一个函数调用,而不是错误IMO):

< blockquote>

json:Unmarshal(nil * main.Animal)



<这似乎是因为 animals 是一个未初始化的指针。但是文档说(强调我的):


解组将指向JSON的值解组为指针指向的值。 如果指针为零,Unmarshal会为它指定一个新值。

解组错误在第二个示例中失败并显示不明确的错误?

(另外,它是解组还是解组(一个L)?文档同时使用)。

解决方案

您遇到 InvalidUnmarshalError (参见 decode.go中的第109行和第110行)。
$ b


// InvalidUnmarshalError描述传递给Unmarshal。

// (Unmarshal的参数必须是非零指针。)


看起来文档可以做一些澄清,如上面的引用和下面的注释来自 Unmarshal 来源似乎相互矛盾。 / p>


如果指针为零,Unmarshal会为它指定一个新值。



This example from the json.Unmarshal docs (slightly modified for simplicity to use Animal instead of []Animal) works, no errors:

Playground link of working example

// ...
var animals Animal
err := json.Unmarshal(jsonBlob, &animals)
// ...

But this slightly modified example doesn't:

Playground link of non-working example

// ...
var animals *Animal
err := json.Unmarshal(jsonBlob, animals)
// ...

It displays this obscure error that really isn't helpful (looks more like a function call than an error IMO):

json: Unmarshal(nil *main.Animal)

This appears to be because animals is an uninitialized pointer. But the docs say (emphasis mine):

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.

So why does unmarshaling fail in the second example and show that obscure error?

(Also, is it "unmarshalling" or "unmarshaling" (one L)? The docs use both.)

解决方案

You've encountered an InvalidUnmarshalError (see lines 109 and 110 in decode.go).

// An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
// (The argument to Unmarshal must be a non-nil pointer.)

It seems the docs could do with some clarification as the quote above and the comment below from the Unmarshal source seem to contradict each other.

If the pointer is nil, Unmarshal allocates a new value for it to point to.

这篇关于为什么json.Unmarshal使用引用而不是指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆