Go-function-call-by-value

提供:Dev Guides
移動先:案内検索

Go-値で呼び出す

引数を関数に渡す*値による呼び出し*メソッドは、引数の実際の値を関数の仮パラメーターにコピーします。 この場合、関数内のパラメーターを変更しても、引数には影響しません。

デフォルトでは、Goプログラミング言語は_call by value_メソッドを使用して引数を渡します。 一般に、これは、関数内のコードが関数の呼び出しに使用される引数を変更できないことを意味します。 次のような関数* 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

関数内で値が変更されていても、値に変更がないことを示しています。