Function arguments are the values passed to a function when it is called. They allow functions to receive input data and perform operations on it. Go always passes arguments by value, meaning a copy of the argument is passed to the function. However, pointers can also be passed, allowing a function to modify the original variable indirectly.
Example: The following example shows that modifying a parameter inside a function does not affect the original variable.
package main
import "fmt"
func modify(num int) {
num = 50
}
func main() {
num := 20
fmt.Printf("Before: %d\n", num)
modify(num)
fmt.Printf("After: %d\n", num)
}
Output
Before: 20 After: 20
Syntax
Go always uses call by value. Even when passing pointers, Go passes a copy of the pointer itself.
Passing Values
func functionName(parameter Type) {
// function body
}
Passing Pointers
func functionName(parameter *Type) {
// function body
}
Key Terminologies
- Actual Parameters: The arguments passed to a function.
- Formal Parameters: The parameters received by the function.
For example:
add(10, 20)
Here, 10 and 20 are actual parameters and parameters declared inside add(a, b int) are formal parameters.
Passing Arguments by Value
Go always passes arguments by value. This means a copy of the variable is passed to the function, and any changes made inside the function do not affect the original variable.
package main
import "fmt"
func increment(num int) {
num++
fmt.Println("Inside function:", num)
}
func main() {
x := 5
fmt.Println("Before function call:", x)
increment(x)
fmt.Println("After function call:", x)
}
Output
Before function call: 5 Inside function: 6 After function call: 5
Explanation:
- increment() accepts an integer parameter.
- increment(x) passes a copy of x.
- num++ modifies only the copied value.
- The original variable x remains unchanged.
Passing Pointers to Functions
Although Go always uses call by value, pointers can be passed to functions, allowing them to modify the original variable indirectly.
package main
import "fmt"
func modify(num *int) {
*num = 50
}
func main() {
num := 20
fmt.Printf("Before: %d\n", num)
modify(&num)
fmt.Printf("After: %d\n", num)
}
Output
Before: 20 After: 50
Explanation:
- modify() accepts a pointer parameter *int.
- &num passes the memory address of num.
- *num = 50 updates the original value.
- The changes are reflected in main().
Note: This is not call by reference. Go passes a copy of the pointer, but both pointers still refer to the same underlying variable.