elseif ((ucp->uc_stack.ss_sp == NULL) || (ucp->uc_stack.ss_size < MINSIGSTKSZ)) { /* * This should really return -1 with errno set to ENOMEM * or something, but the spec says that makecontext is * a void function. At least make sure that the context * isn't valid so it can't be used without an error. */ ucp->uc_mcsize = 0; }
functest() Parent { // c 是一个 Parent 类型 c := createChild()
s := `{"name":"123"}` err := json.Unmarshal([]byte(s), &c) if err != nil { panic(err) }
// 问题:这里能不能得到 name 的值 123? fmt.Printf("name=%s\n", c.(Child).Name)
return c }
答案:不行。
问题描述
具体就是,我有一个结构体 Child 实现了接口
Parent,然后 Child 里面有 name
属性,然后在反序列化的时候,用指向
Parent,类型的值来接收。
结果就是,结构体里面字段都丢失了。
如果我们写成下面这样,就可能错过了发现错误的机会(我一开始就是这么写的):
1
_ = json.Unmarshal([]byte(s), &c)
如果打印错误的话,其实编译器已经给出了明确的报错信息:
1 2
panic: json: cannot unmarshal object into Go value of type body.Parent [recovered] panic: json: cannot unmarshal object into Go value of type body.Parent
You can marshal from an interface type variable, because the object
exists locally, so the reflector knows the underlying type.
You cannot unmarshal to an interface type, because the reflector does
not know which concrete type to give to a new instance to receive the
marshaled data.
$ docker exec -it mysqldb bash # mysql -h localhost -u root -p (now enter the passsword 123456 and hit enter) mysql> create user 'root'@'%' identified WITH mysql_native_password by '123456'; mysql> grant all privileges on *.* to 'root'@'%' with grant option;