目录

Call by value

将参数传递给函数的value call by value方法将参数的实际值复制到函数的形式参数中。 在这种情况下,对函数内部参数所做的更改不会对参数产生影响。

默认情况下,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

它表明尽管在函数内部已经更改,但值没有变化。

↑回到顶部↑
WIKI教程 @2018