Returning Pointer from a Function in Go
Prerequisite: Pointers in Go and Passing Pointers to Function
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function in Golang. In C/C++, it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns. So to execute the concept of returning a pointer from function in C/C++ you must define the local variable as a static variable.
Example: In the below program, the line of code(int lv = n1 * n1;) will give warning as it is local to the function. To avoid warnings make it static.
#include <iostream>
using namespace std;
int * rpf( int );
int main()
{
int n = 745;
cout << n << endl;
cout << *rpf(n) << endl;
}
int * rpf( int n1)
{
int lv = n1 * n1;
return &lv;
}
|
Warnings
prog.cpp: In function ‘int* rpf(int)’:
prog.cpp:24:9: warning: address of local variable ‘lv’ returned [-Wreturn-local-addr]
int lv = n1 * n1;
Output:
745
The main reason behind this scenario is that compiler always make a stack for a function call. As soon as the function exits the function stack also get removed which causes the local variables of functions goes out of scope. Making it static will resolve the problem. As static variables have a property of preserving their value even after they are out of their scope.
But the Go compiler is very Intelligent!. It will not allocate the memory on the stack to the local variable of the function. It will allocate this variable on the heap. In the below program, variable lv will have the memory allocated on the heap as Go compiler will perform escape analysis to escape the variable from the local scope.
Example:
package main
import "fmt"
func main() {
n := rpf()
fmt.Println( "Value of n is: " , *n)
}
func rpf() * int {
lv := 100
return &lv
}
|
Output:
Value of n is: 100
Note: Golang doesn’t provide any support for the pointer arithmetic like C/C++. If you will perform then the compiler will throw an error as invalid operation.
Last Updated :
17 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...