英文:
Golang Unmarshalling behaviour: Excess fields?
问题
假设我有这个结构体:
type MyStruct struct {
A string `json:"a"`
}
但是我收到的响应是这样的:
{"a": "something", "b": "something", "c": "something"}
也就是说,有比预期更多的字段,但我们只想要字段 A。在 Golang 中,将响应解组成 MyStruct 是否安全/允许?
英文:
Suppose I have this struct:
type MyStruct struct {
A string `json:"a"`
}
But I receive a response of the form:
{"a": "something", "b": "something", "c": "something"}
i.e. There are more fields than expected, but we only want the field A. Is it safe/allowed in golang to unmarshal the response into MyStruct?
答案1
得分: 3
是的,它是安全的,有时甚至会有意使用。如果你只需要输入中的几个字段,你可以定义一个只包含这些字段的结构。实际上,如果输入中有未解组的字段,要检测到它们更加困难。
英文:
Yes, it is safe, and even used sometimes intentionally. If you need only a few fields from an input, you can define a structure that includes only those fields. In fact, it is harder to detect if there are fields in the input that are left unmarshaled.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论