Go语言中函数的参数传递与调用的基本方法

2019-11-10 10:00:28于丽

   var a int = 100
   var b int= 200

   fmt.Printf("Before swap, value of a : %dn", a )
   fmt.Printf("Before swap, value of b : %dn", 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 : %dn", a )
   fmt.Printf("After swap, value of b : %dn", 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 */
}

让我们把上面的代码放在一个C文件,编译并执行它,它会产生以下结果:

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

这表明变化的功能以及不同于通过值调用的外部体现的改变不能反映函数之外。