×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

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:

  1. Which symbol is used to pass the address of a variable?
  2. What does the * symbol do in the function receiving a pointer?
  3. Can you modify the original struct data using a pointer?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.