Go language function values pass values
Passing means that a copy of the actual parameter is passed to the function when the function is called, so that if the parameter is modified in the function, the actual parameter will not be affected.
By default Go
language uses value passing, that is, the actual parameters are not affected during the call.
The following definitions swap()
function:
/* Define functions that exchange values with each other */
func swap(x, y int) int {
var temp int
temp = x /* Save the value of x */
x = y /* Assign y value to x */
y = temp /* Assign the temp value to y*/
return temp;
}
Next, let’s use value passing to call the swap()
function:
package main
import "fmt"
func main() {
/* Define local variables */
var a int = 100
var b int = 200
fmt.Printf("The value of a before exchange is : %d\n", a )
fmt.Printf("The value of b before exchange is : %d\n", b )
/* Exchange values by calling functions */
swap(a, b)
fmt.Printf("The value of a after exchange: %d\n", a )
fmt.Printf("The value of b after exchange: %d\n", b )
}
/* Define functions that exchange values with each other */
func swap(x, y int) int {
var temp int
temp = x /* Save the value of x */
x = y /* Assign y value to x */
y = temp /* Assign the temp value to y*/
return temp;
}
The following code execution results are:
The value of a before exchange is: 100
The value of b before exchange is: 200
Value of a after exchange: 100
Value of b after exchange: 200
Value passing is used in the program, so the two values do not interact with each other, and we can use reference passing to achieve the exchange effect.