The Go language allows pointers to be passed to functions by setting thepointer type on the parameters defined by the function.
The following example shows how to pass a pointer to a function and modify the value within the function after the function call: The above example allows the output result to be: 2.35.1. Example #
package main import "fmt" func main() { /* Define local variables */ var a int = 100 var b int= 200 fmt.Printf("Value of a before exchange : %d\\n", a ) fmt.Printf("Value of b before exchange : %d\\n", b ) /* Calling a function to exchange values * &a Address pointing to variable a * &b Address pointing to variable b */ swap(&a, &b); fmt.Printf("The value of a after exchange: %d\\n", a ) fmt.Printf("The value of b after exchange: %d\\n", b ) } func swap(x *int, y *int) { var temp int temp = *x /* Save the value of x address */ *x = *y /* Assign y to x */ *y = temp /* Assign temp to y */ }
Value of a before exchange: 100 Value of b before exchange: 200 Value of a after exchange: 200 Value of b after exchange: 100