Go語言通過參照呼叫函式

2019-10-16 23:16:50

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

要通過參照傳遞值,須將引數指標傳遞給函式,就像傳遞其他值一樣。 因此,需要將函式引數宣告為指標型別,如以下函式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

這表明更改已反映在函式外部,這種呼叫不像通過值呼叫引數值的更改不反映在函式外部。