Go語言按值呼叫函式

2019-10-16 23:16:49

通過傳遞引數到函式的方法的呼叫是指將引數的實際值複製到函式的形式引數中。 在這種情況下,在函式中對引數所做的更改不會影響引數值。

預設情況下,Go程式設計語言使用按值呼叫方法傳遞引數。 一般來說,函式中的程式碼不能改變傳入函式的引數。參考函式swap()定義如下。

/* function definition to swap the values */
func swap(int x, int y) int {
   var temp int

   temp = x /* save the value of x */
   x = y    /* put y into x */
   y = temp /* put temp into y */

   return temp;
}

現在,通過傳遞實際值來呼叫函式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 */
   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, y int) int {
   var temp int

   temp = x /* save the value of x */
   x = y    /* put y into x */
   y = temp /* put temp into y */

   return temp;
}

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

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

這表明,雖然引數在函式內部已更改,但引數的值在外部並沒有更改。