Struct field as pointer or not

Hi,

Tried to find info on web but couldn’t so asking here.

Why would one use a pointer field as seen below? Why should one be preferred over the other one? For example: memory, performance, comparison options …

type Request struct {
	Name              *string `json:"name"`
	No                *uint16 `json:"no"`
	Address           *string `json:"address"`
	CreatedAt         *string `json:"created_at"`
	IsActive          *bool   `json:"is_active"`
}
type Request struct {
	Name              string `json:"name"`
	No                uint16 `json:"no"`
	Address           string `json:"address"`
	CreatedAt         string `json:"created_at"`
	IsActive          bool   `json:"is_active"`
}
var r Request
d := json.NewDecoder(httprequest.body)
d.DisallowUnknownFields()
e := d.Decode(&r)

In general a pointer avoids copying of the data, though it leaks mutability.

For JSON serialisable (and for many other serialisation formats) it does also annotate “optionality of the field”.

in addition to @NobbZ answer, in some cases, you need to distinguish zero values from null/nil.

Lets’s say you have a boolean field named replied

type Answer struct{
    ID int  `json:"id"`
    Replied bool `json:"replied"`
}
// data:`{"id": 1}
// data:`{"id": 1, "replied": false}

When you unmarshal above JSON strings to the an Answer object, you will end up having replied false for both. When you have the concrete object you won’t know why the replied is false, it is because user hasn’t replied yet, or there was no replied key in the JSON. To overcome this ambiguity you need to change replied field to boolean pointer and then you will have nil replied for {"id": 1}

go zero values

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.