Go語言按值調用函數

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

默認情況下,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

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


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