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_functions.htm
廣告
© . All rights reserved.