Golang program to implement returning pointer from a function


In this article, we will write Golang programs to implement returning pointer from a function. A pointer stores the address of another variable and the address is depicted using & operator.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and Output.

  • Step 2 − Create a function create_pointer that returns a pointer to the int

  • Step 3 − Set the value of x in the function and return the variable back to the function

  • Step 4 − Create a main and in that function receive the returned pointer in the ptr variable

  • Step 5 − In this step, print the value pointed to by the pointer on the console using the Println function from the fmt package

Example 1

In this example, a function is created which returns a pointer that points to a particular value and is received inside the variable.

package main

import "fmt"

func create_pointer() *int {
   x := 62
   return &x
}

func main() {
   ptr := create_pointer()	
   fmt.Println("The value pointed to by the pointer is:")
   fmt.Println(*ptr) 
}

Output

The value pointed to by the pointer is:
62

Example 2

In this illustration, a function takes the pointer pointing to the variable as a parameter and that value is updated inside the function. The updated value will be printed on the console with a pointer to the value sent as the argument.

package main

import "fmt"
func update_value(ptr *int) {
   *ptr = 62
}

func main() {	
   a := 0
   update_value(&a)	
   fmt.Println("The value pointed to by the pointer is:")
   fmt.Println(a) 
}

Output

The value pointed to by the pointer is:
62

Example 3

In this example, we will write a Golang program to implement returning pointer from a function by returning the pointer to the struct. The pointer returned will be printed using the dereferencing operator.

package main

import "fmt"

type Person struct {
   name string
   age  int
}
func create_person_pointer() *Person {
   ps := Person{name: "Tanishq", age: 36}
   return &ps
}
func main() {
   ptr := create_person_pointer()
   fmt.Println(*ptr)
	
   ptr.age = 30
   fmt.Println(*ptr)
}

Output

{Tanishq 36}
{Tanishq 30}

Conclusion

We compiled and executed the program of returning a pointer from a function using three examples. In the first example, we returned the pointer variable pointer to int which was printed on the console using the pointer, in the second example, we take the pointer as an argument and update the value and in the third example we returned a pointer to the struct.

Updated on: 04-Apr-2023

443 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements