英文:
Golang structure field's name and unmarshalling into this structure
问题
我写了一个示例程序来说明我的问题,可以在这里查看:https://play.golang.org/p/6776lYcbBR
所以我的问题是:
当一个结构体(GameOne)的字段名以大写字母开头时,json.Unmarshal按预期工作;
当它以小写字母开头(GameTwo)时,字段值被设置为默认值。
为什么会这样?这与作用域/可见性规则有关吗?
提前谢谢。
英文:
I wrote an example program to illustrate my question, and it can be viewed here:
https://play.golang.org/p/6776lYcbBR
So my question is:
when a structure (GameOne) field's name starts with a capital letter, json.Unmarshal works as expected;
when it starts with a lower-case letter (GameTwo), the field value is set to its default.
Why is this so? Has it something to do with scope/visibility rules?
Thank you in advance.
答案1
得分: 1
json.Unmarshal
只会设置结构体中的导出字段,而要导出一个字段,首字母必须是大写的。
如果需要更多信息,我强烈建议你查看文档。
英文:
json.Unmarshal
sets only the export fields in a struct and for exporting a field the first letter must be capital.
For more information I highly suggest you to take a look to the documentation
答案2
得分: 1
根据文档(已加粗部分):
Unmarshal 只会设置结构体中的公开字段。
以小写字母开头的字段显然是不公开的。因此,JSON 编组器(或者实际上是你的包之外的任何东西)都无法影响它们。
英文:
From the documentation (emphasis added):
> Unmarshal will only set exported fields of the struct.
Fields which begin with a lowercase letter are, of course, not exported. So there's no way for the JSON marshaler (or indeed anything at all outside of your package) to affect them.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论