3

EDIT: I feel this question is not a duplicate, as the referenced Q&A do not describe JSON in the use cases.

I have a struct nested within another struct that I use for JSON operations.

In a simple test case, using a copy of a nested struct:

type A struct {
    Foo string
    Bar B
}

type B struct {
    Baz string
}

func main() {
    serialized := `{"foo": "some", "bar": {"baz": "thing"}}`
    a := &A{}
    json.Unmarshal([]byte(serialized), a)
    fmt.Println(a.Foo, a.Bar.Baz)
}
> some thing

yields the same results as using a pointer to a nested struct:

type A struct {
    Foo string
    Bar *B
}

type B struct {
    Baz string
}

func main() {
    serialized := `{"foo": "some", "bar": {"baz": "thing"}}`
    a := &A{}
    json.Unmarshal([]byte(serialized), a)
    fmt.Println(a.Foo, a.Bar.Baz)
}
> some thing

When would or would I not want to use a pointer?

noamt
  • 7,397
  • 2
  • 37
  • 59
  • 2
    As demonstrated, if you have a pointer to the top level structure, the json package can write the data where it needs to go. Use a pointer when you need a pointer. – JimB Apr 23 '19 at 14:43
  • 1
    @noamt, since it works either way, the fact that you happen to use the type for JSON decoding has no bearing on the pointer vs non-pointer decision. I agree that this is a duplicate. – Peter Apr 23 '19 at 15:47
  • 4
    In a struct that represents a JSON object, using a pointer allows you to represent a null value. Thus, with `Bar *B`, you can tell the difference between `{"foo": "some", "bar": {"baz": ""}}` and `{"foo": "some"}` (or `{"foo": "some", "bar": null}`). That point is not covered in the referenced post. – Andy Schweig Apr 23 '19 at 15:52

0 Answers0