Home »
Golang
Go Call by Reference
Last Updated : July 19, 2025
In Go, the language does not support Call by Reference directly like some other languages (e.g., C++), but you can achieve the same effect by passing pointers to functions. When you pass a pointer, the function receives the memory address of the variable, so it can modify the original data.
Understanding Call by Reference
To simulate Call by Reference in Go, you pass the address of the variable (using &
) to the function, and the function uses a pointer (using *
) to modify the original value.
Example: Call by Reference in Go
The following example shows how to use pointers in Go to modify the original variable's value within a function:
package main
import "fmt"
func update(num *int) {
*num = *num + 10
fmt.Println("Inside function, updated value =", *num)
}
func main() {
value := 20
update(&value)
fmt.Println("Outside function, value =", value)
}
When you run the above code, the output will be:
Inside function, updated value = 30
Outside function, value = 30
Explanation
In the example above:
&value
passes the memory address of value
to the update
function.
*num
accesses the actual value at that memory address.
- So, when
*num
is modified, the original value
is also updated.
Call by Reference with Structs
You can also use pointers to structs to modify their fields from inside functions.
Example: Modifying Struct using Pointer
The following example demonstrates how to use a pointer to a struct in Go to update its fields within a function:
package main
import "fmt"
type Student struct {
name string
age int
}
func incrementAge(s *Student) {
s.age = s.age + 1
fmt.Println("Inside function, updated age =", s.age)
}
func main() {
stu := Student{name: "Rohit", age: 22}
incrementAge(&stu)
fmt.Println("Outside function, age =", stu.age)
}
When you run the above code, the output will be:
Inside function, updated age = 23
Outside function, age = 23
When to Use Call by Reference
- When you want to modify the original value.
- To avoid copying large structs or arrays, improving performance.
- When multiple functions need to work on the same data.
Exercise
Test your understanding of Call by Reference in Go:
- Which symbol is used to pass the address of a variable?
- What does the
*
symbol do in the function receiving a pointer?
- Can you modify the original struct data using a pointer?
Advertisement
Advertisement