Function Arguments in Golang
Last Updated :
29 Oct, 2024
In Golang, functions are groups of statements used to perform tasks, with optional returns. Go supports two main ways to pass arguments: Pass by Value and Pass by Reference. By default, Go uses pass-by-value.
Basic Terms in Parameter Passing to Functions:
- Actual Parameters: The arguments passed to a function.
- Formal Parameters: The parameters received by the function.
Example
package main
import "fmt"
// Attempts to modify the value of num
func modify(num int) {
num = 50
}
func main() {
num := 20
fmt.Printf("Before, num = %d\n", num)
modify(num)
fmt.Printf("After, num = %d\n", num)
}
In this example, num
remains unchanged after calling modify
since it’s passed by value.
Syntax
func functionName(param Type) {
// function body # Call By Value
}
func functionName(param *Type) {
// function body # Call By Reference
}
Call By Value
In call-by-value, a copy of the actual parameter’s value is passed. Changes made in the function don’t affect the original variable.
Syntax
func functionName(param Type) {
// function body
}
Example:
Go
package main
import "fmt"
// Attempts to modify the value of num
func modify(num int) {
num = 50
}
func main() {
num := 20
fmt.Printf("Before, num = %d\n", num)
modify(num)
fmt.Printf("After, num = %d\n", num)
}
OutputBefore, num = 20
After, num = 20
The value remains the same, as changes inside modify
don’t impact num
in main
.
Call By Reference
In call-by-reference, a pointer to the actual parameter is passed, so any changes inside the function reflect on the original variable.
Syntax
func functionName(param *Type) {
// function body
}
Example:
Go
package main
import "fmt"
// Modifies value of num via reference
func modify(num *int) {
*num = 50
}
func main() {
num := 20
fmt.Printf("Before, num = %d\n", num)
modify(&num)
fmt.Printf("After, num = %d\n", num)
}
OutputBefore, num = 20
After, num = 50
Since num
is passed by reference, modify
changes its value, which is reflected in main
.