Go-passing-pointers-to-functions

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

Go-ポインターを関数に渡す

Goプログラミング言語では、ポインターを関数に渡すことができます。 そのためには、単に関数パラメーターをポインター型として宣言します。

次の例では、2つのポインタを関数に渡し、呼び出し元の関数に反映される関数内の値を変更します-

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*/
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

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