位置:首頁 > 高級語言 > Go語言教學 > Go語言傳遞指針到函數

Go語言傳遞指針到函數

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