tygar
tygar

Reputation: 264

When to use pointers when defining structs

Ive noticed in some libraries that when they define structs some values have pointers while others don't. I can't seem to find anywhere explaining when to use pointers and when not to.

Example

type MyStruct struct {
     FieldOne     *int64 
     FieldTwo     int64
     FieldFour    *AnotherStruct
     FieldFive    AnotherStruct
}

What are the benefits of using a pointer ?

Upvotes: 1

Views: 120

Answers (1)

Farmer
Farmer

Reputation: 19

From my experience, I will try to not use pointer value in a struct because it may be root cause of panic, if we forgot to check nil before use it. Have three reason when I use a pointer value in a struct:

  1. This field is a big struct so I think it can help to reduce copy costs (It's correct in C/C++, but in go, some case the Benchmark test showed same result).
  2. When I need to check and do some thing if this value is nil (Because of default values in go and the cost to compare with AnotherStruct{}).
  3. When i need "omitempty" (ignore this field if it empty) to convert fields of struct to bson or json ... I hope 2) and 3) can help to answers for your question. If you have any better idea please share me. Because I also new on go!

Upvotes: 1

Related Questions