Home >Backend Development >Golang >Golang unmarshaling behavior: extra fields?

Golang unmarshaling behavior: extra fields?

PHPz
PHPzforward
2024-02-09 10:57:26585browse

Golang 解组行为:多余字段?

php editor Strawberry brings you the latest technical analysis - "Golang unmarshaling behavior: redundant fields?". When using Golang to unmarshal, we often encounter a problem: when there are redundant fields in the target structure, how will the unmarshaling operation be handled? This article will answer this question in detail for you and provide some solutions to help you better understand and apply Golang's unmarshaling mechanism. Whether you are a beginner or an experienced developer, I believe this article can bring you some new inspiration and help. Let’s dive in!

Question content

Suppose I have this structure:

type mystruct struct {
    a string `json:"a"`
}

But I received a response of the following form:

{"a": "something", "b": "something", "c": "something"}

That is, there are more fields than expected, but we only want field a. Is it safe/allowed to unmarshal response into mystruct in golang?

Workaround

Yes, it is safe and even used intentionally sometimes. If you only need a few fields from the input, you can define a structure containing only those fields. In fact, it is more difficult to detect the presence of unmarshalled fields in the input.

The above is the detailed content of Golang unmarshaling behavior: extra fields?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete