A function in Golang is a collection of statements which is used to perform specific task and return the result to the caller. A function can also perform some specific task without returning anything. Golang supports two different ways to pass arguments to the function i.e. Pass by Value or Call by Value and Pass By Reference or Call By Reference. By default, Golang uses the call by value way to pass the arguments to the function.
Basic Terms in Parameter Passing to Function:
- The parameters passed to function are called Actual Parameters.
- The parameters received by the function are called Formal Parameters.
Call By Value
In this parameter passing, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller.
Example 1: In the below program, you can see that the value of Z cannot be modified by the function modify.
Before Function Call, value of Z is = 10 After Function Call, value of Z is = 10
Example 2: In the below program, swap function is unable to swap the values as we are using the call by value.
Values Before Function Call f = 700 and s = 900 Values After Function Call f = 700 and s = 900
Call By Reference
Here, you will use the concept of Pointers. The dereference operator * is used to access the value at an address. The address operator & is used to get the address of a variable of any data type. Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller.
Example 1: In the function call, we are passing the address of the variable and using the dereferencing operator * to modify the value. So after the function i.e. modify, you will find the updated value.
Before Function Call, value of Z is = 10 After Function Call, value of Z is = 70
Example 2: By using the call by reference the swap function will be able to swap the values as shown below.
Values Before Function Call f = 700 and s = 900 Values After Function Call f = 900 and s = 700