This question already has an answer here:
Reviewing some go code I came across this:
Person struct {
Name *string `json:"name"`
}
and then some where I saw:
Animal struct {
Name string `json:"name"`
}
What is the advantage of the pointer here?
</div>
The *
declares a pointer type. A pointer to a string is sometimes used when decoding JSON to distinguish the following JSON:
JSON value of the Name field
{ } nil
{name: ""} pointer to ""
Without the pointer, it's not possible to distinguish a missing value from a blank value in the decoded result.
If the application does not need to make this distinction, then use the second form shown in the question. It's more convenient.
*
means pointer.
In your case, Name
is a field of type pointer to string.
The *
is a pointer.
A pointer type denotes the set of all pointers to variables of a given type, called the base type of the pointer. The value of an uninitialized pointer is nil.
This is coming from the Go Spec. I would suggest reading it all.