Go language pointers as function parameters
Go language allows passing pointers to functions; you just need to set the parameter type as a pointer in the function definition.
The following example demonstrates how to pass pointers to functions 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 : %d\n\n", a )
fmt.Printf("Value of b before swap : %d\n\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("Value of a after swap : %d\n\n", a )
fmt.Printf("Value of b after swap : %d\n\n", b )
}
func swap(x *int, y *int) {
var temp int
temp = *x /* Save the value at x's address */
*x = *y /* Assign y to x */
*y = temp /* Assign temp to y */
}
import "fmt"
func main() {
/* Define local variables */
var a int = 100
var b int= 200
fmt.Printf("Value of a before swap : %d\n\n", a )
fmt.Printf("Value of b before swap : %d\n\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("Value of a after swap : %d\n\n", a )
fmt.Printf("Value of b after swap : %d\n\n", b )
}
func swap(x *int, y *int) {
var temp int
temp = *x /* Save the value at x's address */
*x = *y /* Assign y to x */
*y = temp /* Assign temp to y */
}
The above examples may output the following result:
交换前 a 的值 : 100 交换前 b 的值 : 200 交换后 a 的值 : 200 交换后 b 的值 : 100other extensions