Go Language Pointers as Function Parameters
Go language allows passing pointers to functions by simply setting the function's parameter to a pointer type.
The following example demonstrates how to pass pointers to a function and modify the values inside the function after the call:
Example
package main
import "fmt"
func main() {
/* Define local variables */
var a int = 100
var b int = 200
fmt.Printf("Before swap, value of a : %d\n", a )
fmt.Printf("Before swap, value of b : %d\n", b )
/* Call the function to swap values
* &a points to the address of variable a
* &b points to the address of variable b
*/
swap(&a, &b);
fmt.Printf("After swap, value of a : %d\n", a )
fmt.Printf("After swap, value of b : %d\n", b )
}
func swap(x *int, y *int) {
var temp int
temp = *x /* Save the value at address x */
*x = *y /* Assign y's value to x */
*y = temp /* Assign temp's value to y */
}
The output of the above example is:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100