Go language function value passing

Go functions

Passing means copying the actual parameters and passing them to the function when calling it, so that if the parameters are modified inside the function, it will not affect the actual parameters.

By default, Go uses value passing, which means the actual parameters are 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 use value passing to call the swap() function:

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 values by calling a function */
   swap(a, b)

   fmt.Printf("Value of a after swap : %d\n\n", a )
   fmt.Printf("Value of b after swap : %d\n\n", b )
}

/* Define a function that swaps 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 execution result of the following code is:

交换前 a 的值为 : 100
交换前 b 的值为 : 200
交换后 a 的值 : 100
交换后 b 的值 : 200

The program uses value passing, so the two values did not interact. We can usePass by referenceTo achieve the swapping effect.

Go functions

other extensions