package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
}
func main() {
var u User
fmt.Printf("u=%+v, &u=%p/n", u, &u) //output: u={Name:}, &u=0xc00003e230
json.Unmarshal([]byte(`{"name":"polaris"}`), &u)
fmt.Printf("u.Name=%+v/n", u.Name) //output: u.Name=polaris
//var u1 *User
//fmt.Printf("u1=%+v, &u1=%p/n", u1, &u1) //output: u1=<nil>, &u1=0xc00007a028
//json.Unmarshal([]byte(`{"name":"polaris"}`), u1)
////以上会直接报错:panic: runtime error: invalid memory address or nil pointer dereference
//fmt.Printf("u1.Name=%+v/n", u1.Name)
var u2 *User
fmt.Printf("u2=%+v, &u2=%p/n", u2, &u2) //output: u2=<nil>, &u2=0xc00007a028
json.Unmarshal([]byte(`{"name":"polaris"}`), &u2)
fmt.Printf("u2.Name=%+v/n", u2.Name) //正常打印出u2.Name=polaris
/**
总结:
json.Unmarshal()第二个参数必须传入一个有内存地址的变量
*/
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/18137.html