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;
}

將以上程式碼放在單個 C 檔案中,然後編譯並執行它。它將產生以下結果 −

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