Pointers as Function Parameters in Go
Go allows passing pointers to functions; you only need to set the parameter in the function definition to a pointer type.
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
()
{
/* Define local variables */
var
a
int
=
100
var
b
int
=
200
fmt
.
Printf
(
"value of a before swap : %d\n"
,
a
)
fmt
.
Printf
(
"value of b before swap : %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, the value of a is : %d\n"
,
a
)
fmt
.
Printf
(
"After swap, the value of b is : %d\n"
,
b
)
}
func
swap
(
x
int
,
y
int
)
{
var
temp
int
temp
=
x
/* store the value at address x */
x
=
y
/* assign y to x */
y
=
temp
/* assign temp to y */
}
The above example allows the following output:
交换前 a 的值 : 100
交换前 b 的值 : 200
交换后 a 的值 : 200
交换后 b 的值 : 100
Go Pointers