当前位置: 首页 > 文档资料 > Go 语言中文教程 >

Passing pointers to functions in Go

优质
小牛编辑
117浏览
2023-12-01

Go编程语言允许您传递指向函数的指针。 为此,只需将函数参数声明为指针类型即可。

在下面的示例中,我们传递两个指向函数的指针并更改函数内部的值,该值反映在调用函数中 -

package main
import "fmt"
func main() {
   /* local variable definition */
   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 )
   /* calling a function to swap the values.
   * &a indicates pointer to a ie. address of variable a and 
   * &b indicates pointer to b ie. 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      /* put y into x */
   *y = temp    /* put temp into y */
}

编译并执行上述代码时,会产生以下结果 -

Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100