Home > Article > Backend Development > 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!