WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - Passing pointers to functions


Go language allows pointers to be passed to functions, just by setting them to pointer types on the parameters defined by the function.

The following example demonstrates how to pass a pointer to a function and modify the value inside the function after the function call:

example

package main

import "fmt"

func main() {
   /* Defining local variables */
   var a int = 100
   var b int= 200

   fmt.Printf("Before exchange a Value : %d\n", a )
   fmt.Printf("Before exchange b Value : %d\n", b )

   /* Call function to exchange values
   * &a direction a Variable address
   * &b direction b Variable address
   */

   swap(&a, &b);

   fmt.Printf("After exchange a Value : %d\n", a )
   fmt.Printf("After exchange b Value : %d\n", b )
}

func swap(x *int, y *int) {
   var temp int
   temp = *x    /* Save x address Value */
   *x = *y      /* will y Assignment tox */
   *y = temp    /* Assign temp to y */
}

The above example allows the output to be:

Before exchange a Value : 100
Before exchange b Value : 200
After exchange a Value : 200
After exchange b Value : 100