<分区>
我正在使用 golang 来解析一个 json 字符串:
str:="{...}"
var f interface{}
json.Unmarshal([]byte(str), f)
fmt.Println(f)
虽然我在控制台中得到了 nil
。
当我将代码更改为:
json.Unmarshal([]byte(str), &f)
它将打印 json 字符串。
这是怎么回事?
<分区>
我正在使用 golang 来解析一个 json 字符串:
str:="{...}"
var f interface{}
json.Unmarshal([]byte(str), f)
fmt.Println(f)
虽然我在控制台中得到了 nil
。
当我将代码更改为:
json.Unmarshal([]byte(str), &f)
它将打印 json 字符串。
这是怎么回事?
最佳答案
有两件事正在发生:
json.Unmarshal
的返回值来检查错误。来自fine manual :
func Unmarshal(data []byte, v interface{}) error
Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.
Unmarshal
采用接口(interface){}
,因为它可以解码为文档中所述的各种事物( slice 、映射、结构...)。
关于pointers - golang 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48482930/