Pass by pointers vs. values and return values in golang. What are the best practices?

Ritesh swamy Responses • 2 Posted • Jun 21 2019
In Go there are various ways to return a struct value or slice thereof. For individual ones I've seen:
type MyStruct struct { Val int } func myfunc() MyStruct { return MyStruct{Val: 1} } func myfunc() *MyStruct { return &MyStruct{} } func myfunc(s *MyStruct) { s.Val = 1 }

I understand the differences between these. The first returns a copy of the struct, the second a pointer to the struct value created within the function, the third expects an existing struct to be passed in and overrides the value.

I've seen all of these patterns be used in various contexts, I'm wondering what the best practices are regarding these.

When would you use which? For instance, the first one could be ok for small structs (because the overhead is minimal), the second for bigger ones. And the third if you want to be extremely memory efficient, because you can easily reuse a single struct instance between calls. Are there any best practices for when to use which?

Write your response...

On a mission to build Next-Gen Community Platform for Developers