Recently, users have noticed unexpected behavior using json.Unmarshal when passing pointers. Let's investigate why the difference exists.
In the official documentation, we encounter a statement that suggests Unmarshal auto-allocates a new value to point to if the pointer is initially nil:
Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates a new value for it to point to.
However, when attempting to use Unmarshal with an uninitialized pointer, we encounter an InvalidUnmarshalError:
// An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
// (The argument to Unmarshal must be a non-nil pointer.)
This error conflicts with the documentation's suggestion of automatic memory allocation.
To resolve this discrepancy, it's crucial to address the subtle difference between using a reference and a pointer. In the first example where the code works, the usage of &animals creates a reference to the variable, ensuring it's always non-nil. This reference behavior aligns with the expected functionality.
In contrast, the second example uses an uninitialized pointer (*animals), which represents an invalid argument in the eyes of Unmarshal. The error it generates reflects this issue accurately.
As a final note, the correct spelling of the word is "unmarshaling," per the official documentation.
The above is the detailed content of Why Does `json.Unmarshal` Throw an `InvalidUnmarshalError` When Using an Uninitialized Pointer?. For more information, please follow other related articles on the PHP Chinese website!