![]() |
VOOZH | about |
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.
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.
func functionName(param Type) {
// function body # Call By Value
}
func functionName(param *Type) {
// function body # Call By Reference
}
Table of Content
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.
func functionName(param Type) {
// function body
}
Example:
Before, num = 20 After, num = 20
The value remains the same, as changes inside modify don’t impact num in main.
In call-by-reference, a pointer to the actual parameter is passed, so any changes inside the function reflect on the original variable.
func functionName(param *Type) {
// function body
}
Example:
Before, num = 20 After, num = 50
Since num is passed by reference, modify changes its value, which is reflected in main.