Go Passing Pointers To Functions
# Go Pointers as Function Parameters
[Go Pointers](#)
Go allows passing pointers to functions. You just need to set the parameter in the function definition to a pointer type.
The following example demonstrates how to pass pointers to a function and modify the values within the function after the function call:
## Example
package main
import"fmt"
func main(){
/* Define local variables */
var a int=100
var b int=200
fmt.Printf("Value of a before swap: %dn", a )
fmt.Printf("Value of b before swap: %dn", 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("Value of a after swap: %dn", a )
fmt.Printf("Value of b after swap: %dn", b )
}
func swap(x *int, y *int){
var temp int
temp =*x /* Save the value at address x */
*x =*y /* Assign y to x */
*y = temp /* Assign temp to y */
}
The output of the above example is:
Value of a before swap: 100Value of b before swap: 200Value of a after swap: 200Value of b after swap: 100
[Go Pointers](#)
YouTip