YouTip LogoYouTip

Go Function Call By Value

# Go Language Function Call by Value [![Image 3: Go Functions](#)Go Functions](#) Passing by value means that when calling a function, a copy of the actual parameter is made and passed to the function. If the parameter is modified within the function, it will not affect the actual parameter. By default, Go language uses value passing, meaning the actual parameter is not affected during the call. The following defines a `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 the value of y to x */ y = temp /* Assign the value of temp to y*/ return temp;} Next, let's call the `swap()` function using value passing: ## Example package main import"fmt" func main(){ /* Define local variables */ var a int=100 var b int=200 fmt.Printf("Value of a before swap: %dn", a ) fmt.Printf("Value of b before swap: %dn", b ) /* Call the function to swap values */ swap(a, b) fmt.Printf("Value of a after swap: %dn", a ) fmt.Printf("Value of b after swap: %dn", 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 the value of y to x */ y = temp /* Assign the value of temp to y*/ return temp; } The output of the above code is: Value of a before swap: 100 Value of b before swap: 200 Value of a after swap: 100 Value of b after swap: 200 The program uses value passing, so the two values are not actually swapped. We can use (#) to achieve the swapping effect. [![Image 4: Go Functions](#)Go Functions](#)
← Go Function ClosuresGo Goto Statement β†’