In Golang , a function is a group of statements used to perform tasks, with an optional return value . Go supports two main ways to pass arguments: Pass by value and Pass by reference. Go uses pass by value by default.

Basic terms in passing parameters to functions:
- Actual parameters: The arguments passed to the function.
- Formal parameters: The parameters received by the function.
For example
package main
import "fmt"
// Cố gắng sửa đổi giá trị của 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, numremains unchanged after the call modifybecause it is passed by value.
Syntax
func functionName(param Type) {
// function body # Gọi theo giá trị
}
func functionName(param *Type) {
// function body # Gọi theo tham chiếu
}
Call by value
In call-by-value, a copy of the actual parameter value is passed. Changes made in the function do not affect the original variable.
Syntax
func functionName(param Type) {
// function body
}
For example:
package main
import "fmt"
// Chỉnh sửa giá trị của 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)
}
Result:
Before, num = 20
After, num = 20
The value remains the same, as changes inside modifydo not affect numthe outside main.
Function arguments in Golang
Call by reference
In call-by-reference, a pointer to the actual parameter is passed, so any changes inside the function are reflected on the original variable.
Syntax
func functionName(param *Type) {
// function body
}
For example:
package main
import "fmt"
// Chỉnh sửa giá trị của num qua tham chiếu
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)
}
Result
Before, num = 20
After, num = 50
Since numit is passed by reference, the command modifywill change its value, which is reflected in the command main.