Golang unmarshaling behavior: extra fields?

PHPz
Release: 2024-02-09 10:57:26
forward
550 people have browsed it

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"`
}
Copy after login

But I received a response of the following form:

{"a": "something", "b": "something", "c": "something"}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template