Introduction
While writing a program in Golang (also known as Go), you will write functions and methods and pass data to these functions as arguments. In some cases, you might want to tell the function where the data is located instead of sending the actual data to the function. That is where a Pointer can be really useful for you. A Pointer data type holds the memory address of the data instead of the data itself. We can give pointers to the function and return pointers from a function in Go.
We will understand the need for returning pointer from a function and how we can implement returning pointers in Go. We have also covered Pointers to an Array as Function Arguments in Go, So check that out after going through this article.
The Need for Returning Pointer
When it comes to deciding return from a function while writing a software program, memory usage and efficiency are crucial deciding factors. If we design a function in Golang to return a pointer, there will be an escape, and the resulting variable will be allocated on the heap. Meanwhile, the return will be allocated to the stack if the function returns a value. In terms of memory, Stacks are cheap, and Heaps are expensive (If you are not familiar with Stack and Heap allocations, you can check out our articles like Heap Allocation and Stack Allocation). So why would we need to return a pointer from a function in the first place?
The need of returning a pointer from a function depends on the structure and usage of the business scenario or project. Generally, while returning a resource, it is recommended to return a pointer to a large structure rather than the data itself.
In addition, as soon as the function exits, the function slack is also removed, causing the function's local variable to go out of scope. The Go compiler will allocate this variable on the heap instead of assigning the memory on the stack to the function's local variable. We will look at this implementation, known as escape analysis, in the next section of this article.