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
- How to pass a Slice to Function in Golang?
- main and init function in Golang
- Function as a Field in Golang Structure
- How to pass an Array to a Function in Golang?
- Golang Pointer to an Array as Function Argument
- Zero value in Golang
- Pointers in Golang
- Encapsulation in Golang
- Methods With Same Name in Golang
- Packages in Golang
- Slices in Golang
- Strings in Golang
- Interfaces in Golang
- Channel in Golang
- Recover in Golang
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.