pointers - golang 中的指针

标签 pointers go

<分区>

我正在使用 golang 来解析一个 json 字符串:

str:="{...}"
var f interface{}
json.Unmarshal([]byte(str), f)

fmt.Println(f)

虽然我在控制台中得到了 nil

当我将代码更改为:

json.Unmarshal([]byte(str), &f)

它将打印 json 字符串。

这是怎么回事?

最佳答案

有两件事正在发生:

  1. 您没有阅读文档。
  2. 您没有检查 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/

相关文章:

objective-c - Objective C 中的 C 指针的内存管理如何工作

ajax - Golang、Ajax - 如何在成功函数中返回 slice 或结构?

mongodb - map[string]interface{} 自切换到新的 go mongo 驱动程序后未被正确解析

c - 修改了c中的一个常量

c - Typedef 结构、指针和将指针传递给函数

c++ - C++ 中的指针未正确初始化

reflection - 如何从 refect.Value 获取结构字段

regex - 通过go解释这个正则表达式解释

去字符串插值

c - 这个 const 值是如何改变的..?