Easy Tutorial
❮ Go Environment Go For Loop ❯

Go Language Function Value Passing

Go Functions

Passing refers to copying the actual parameters and passing them to the function when it is called. This ensures that any modifications to the parameters within the function do not affect the actual parameters.

By default, Go uses pass-by-value, meaning that the actual parameters are not affected during the function call.

The following defines the swap() function:

/* Define a function to swap values */
func swap(x, y int) int {
   var temp int

   temp = x /* Save the value of x */
   x = y    /* Assign y's value to x */
   y = temp /* Assign temp's value to 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, value of a : %d\n", a)
   fmt.Printf("Before swap, value of b : %d\n", b)

   /* Call the function to swap values */
   swap(a, b)

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

/* Define a function to swap values */
func swap(x, y int) int {
   var temp int

   temp = x /* Save the value of x */
   x = y    /* Assign y's value to x */
   y = temp /* Assign temp's value to y */

   return temp
}

The output of the code is:

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

Since the program uses pass-by-value, the two values did not swap. To achieve the swapping effect, we can use pass-by-reference.

Go Functions

❮ Go Environment Go For Loop ❯