Go-function-call-by-reference

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

Go-参照による呼び出し

引数を関数に渡す*参照による呼び出し*メソッドは、引数のアドレスを仮パラメーターにコピーします。 関数内では、呼び出しで使用される実際の引数にアクセスするためにアドレスが使用されます。 これは、パラメーターに加えられた変更が、渡された引数に影響することを意味します。

参照によって値を渡すために、引数ポインターは他の値と同様に関数に渡されます。 したがって、次の関数* swap()*のように、関数のパラメーターをポインター型として宣言する必要があります。これは、引数が指す2つの整数変数の値を交換します。

/*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/go_pointers [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

変更が関数の外に反映されない値による呼び出しとは異なり、変更は関数の外にも反映されていることを示しています。