Go語言通過引用調用函數

通過將引數傳遞給函數的引用方法的調用,是指將參數的地址複製到形式參數中。 在函數內部,地址用於訪問在調用中使用的實際參數。 這意味著對參數所做的更改會影響傳遞的參數的值。

要通過引用傳遞值,須將參數指針傳遞給函數,就像傳遞其他值一樣。 因此,需要將函數參數聲明為指針類型,如以下函數swap(),它交換的參數是指向的兩個整數變數的值。

/* function definition to swap the values */
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 */
}

要瞭解學習Go指針的更多資訊,可以查看Go指針章節

現在,通過引用傳遞值來調用函數swap(),如下例所示:

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 */
}

把上面的代碼放在一個單獨的Go檔中,編譯並執行它,它會產生以下結果:

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

這表明更改已反映在函數外部,這種調用不像通過值調用參數值的更改不反映在函數外部。


上一篇: Go語言函數 下一篇: Go語言作用域規則