Why Does `json.Unmarshal` Work with a Reference but Not a Pointer?

Barbara Streisand
Release: 2024-11-12 04:57:01
Original
478 people have browsed it

Why Does `json.Unmarshal` Work with a Reference but Not a Pointer?

Why Does Unmarshal Work with Reference but Not Pointer?

To provide context for this inquiry, in Go, the json.Unmarshal function deserializes JSON data into a struct pointed to by the provided reference. Let's delve into the behavior of Unmarshal in two scenarios.

Scenario 1: Reference to a Struct

In the first scenario, a non-nil reference to a struct is passed to Unmarshal, as in the following snippet:

This works seamlessly. As per the documentation, if the pointer is nil (initialized to zero), Unmarshal allocates a new struct value to point to. However, in this case, animals is already initialized and pointing to a valid struct, so the operation succeeds.

Scenario 2: Pointer to a Struct

In this scenario, an uninitialized pointer to a struct is passed to Unmarshal.

This results in an "invalid argument" error:

This occurs because the documentation is not entirely clear. While it mentions that Unmarshal allocates a new struct if the pointer is nil, it doesn't explicitly state that the pointer itself must be non-nil, as indicated in the following comment in the source code of Unmarshal:

Therefore, passing an uninitialized pointer (which is nil by default in Go) to Unmarshal triggers this error, as it violates the requirement for a non-nil pointer. To resolve this issue, simply initialize the pointer to a new struct before calling Unmarshal.

Spelling of "Unmarshaling"

As for the spelling, both "unmarshalling" and "unmarshaling" are accepted spellings, with the second being more common in Go code according to a grep of the Go source codebase.

The above is the detailed content of Why Does `json.Unmarshal` Work with a Reference but Not a Pointer?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template