-1

I've been looking in many, many places and I couldn't find any satisfying answer for my question: what is the benefit of using pointers to nested structs in Go?

Currently I am total newbie in Go, I started reading a book "Go programming language" and I do every excerice there to make sure I understand the syntax and use case. Until now. The goal of one of tasks was to create very simple GitHub client that retrieves a list of issues filtered by given params. It's an example showing how to use json unmarshalling. So there are some nested structs:

type SearchIssueResult {
    TotalCount int
    Issues []*Issue
}

type Issue {
    Title string
    Author *User
    // ... other properties
}

And here's my question again: Why these nested structs have type of pointers to structs? I can use just struct type and it works as well (with slight modifications in usage of struct's instance) but I would like to understand when to use different approaches.

Thanks!

Kuba T
  • 2,893
  • 4
  • 25
  • 30
  • 3
    Probably related [Pointers vs. values in parameters and return values](https://stackoverflow.com/questions/23542989/pointers-vs-values-in-parameters-and-return-values). – skovorodkin Jun 28 '18 at 17:35

1 Answers1

-2

It depends on how complex your structure is. I'd suggest using pointers every time you refer to a structure. Here are some benefits of this approach:

  1. Referred object can live longer than your structure.
  2. It's faster to make a copy of a pointer than a copy of (complex) structure.

For some basic types like: int, float, string it can be faster to pass it by copy.

Persi
  • 414
  • 6
  • 15