Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Go Function Pass-by-Value

Go Function Pass-by-Value

Go FunctionsGo Functions

Pass-by-value means copying the actual argument and passing the copy into the function when calling it, so any modifications to the parameter inside the function will not affect the actual argument.

By default, Go uses pass-by-value, meaning the actual argument is not affected during the call.

The following defines the swap() function:

/* 定义相互交换值的函数 */

func swap(x, y int) int {

   var temp int



   temp = x /* 保存 x 的值 */

   x = y    /* 将 y 值赋给 x */

   y = temp /* 将 temp 值赋给 y*/



   return temp;

}

Next, let's call the swap() function using pass-by-value:

Example

package

main

import

"fmt"

func

main

()

{

   

/* Define local variables */

   

var

a

int

=

100

   

var

b

int

=

200

   fmt

.

Printf

(

"Before swap, the value of a is : %d\n"

,

a

)

   fmt

.

Printf

(

"Before swap, the value of b is : %d\n"

,

b

)

   

/* Swap the values by calling a function */

   swap

(

a

,

b

)

   fmt

.

Printf

(

"After swap, the value of a is : %d\n"

,

a

)

   fmt

.

Printf

(

"After swap, the value of b is : %d\n"

,

b

)

}

/* Define a function that exchanges the values */

func

swap

(

x

,

y

int

)

int

{

   

var

temp

int

   temp

=

x

/* Save the value of x */

   x

=

y    

/* Assign the value of y to x */

   y

=

temp

/* Assign the value of temp to y*/

   

return

temp

;

}

The following code executes with the result:

交换前 a 的值为 : 100

交换前 b 的值为 : 200

交换后 a 的值 : 100

交换后 b 的值 : 200

The program uses pass-by-value, so the two values are not actually swapped; we can use Pass by reference to achieve the swap effect.

Go FunctionsGo Functions