Home > OS >  Usage of pointers in nest golang structs
Usage of pointers in nest golang structs

Time:11-08

I'm new to golang and learning how dereferencing works in nested struct types. When I searched for nested structs normally they would suggest the method suggested by @OneOfOne in How to initialize a nested struct?

However while reading the codebase at work i noticed the team also uses nested pointers. I'm confused when I should use this. ie. nested struct req Person vs a nested pointer req *Person?

example

  • Person

    type Person struct {
        Name string
        Age  int8
    }
    
  • args

    type args struct {
        req *Person
    }
    

CodePudding user response:

One common use case for pointers in struct attributes (besides struct size) is the optionality of the said attribute. While I do not know about particular use case, I can guess that it might refer to some sort of an optional relationship.

For example: A Customer struct having a LastOrder struct attribute. Since the customer may not even have made a single order yet, it might make sense to keep this as a pointer reference, in order ti signal that it may be nil.

Another use case of using pointer attributes is in graph-like or referential data structures. Think about a Person struct who has both a Mother and a Father attributes. If you set those to be of type Person, the compiler will come back with an error, because the resulting structure will recurse ad-infinitum. In that case, those must be set as pointers too.

Hope the answer helps.

CodePudding user response:

You should use pointers when you want it to be an optional field (because you can simply assign a nil pointer to it when initializing a variable), when a size is big and you want to increase the app's performance, or if you want to have a field that points to a variable of the same type e.g:

type Node struct {
    Data int
    Left *Node
    Right *Node
}
  •  Tags:  
  • go
  • Related