Golang的反序列化行为:多余的字段会怎样处理?

huangapple go评论144阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月2日 12:12:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75318601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定