参数类型为 interface{} 时,为什么传入的是变量的地址

func Unmarshal(data []byte, v interface{}) error 

这个为 json 包的 Unmarshal 方法

var user map[string]interface{}
var data = [..假设这个是 byte 的数组]

在调用的时候,传入的为什么是 
json.Unmarshal(data, &user)
而不是
json.Unmarhsal(data, user)
阅读 4.8k
3 个回答
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 解析 JSON 编码的数据并存储结果

从语法角度上讲:传值只是改变的副本,得传指针才能修改。

虽然看得出来第二个参数是输出参数,其实它的最主要作用,是能够将JSON数据解析为指定的struct结构对象。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题