×

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 Structures

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Passing Pointers to a Function

Last Updated : July 17, 2025

In Go, you can pass pointers to functions to allow them to modify the original values. This is useful when you want to avoid copying data or when you need the function to reflect changes in the caller's variable.

Why Pass Pointers?

When you pass variables by value, a copy is made. If you want the function to update the actual value (not a copy), you need to pass a pointer.

Example

The following example demonstrates how passing a value to a function in Go does not modify the original variable, since arguments are passed by value:

package main
import "fmt"

func update(num int) {
    num = 100
}

func main() {
    x := 50
    update(x)
    fmt.Println("Value of x:", x)
}

This outputs:

Value of x: 50

The value remains unchanged because update receives a copy of x.

Passing a Pointer Instead

To modify the original value, pass the address using a pointer and dereference it inside the function.

Example

The following example demonstrates how passing a pointer to a function allows it to modify the original variable's value in Go:

package main
import "fmt"

func update(num *int) {
    *num = 100
}

func main() {
    x := 50
    update(&x)
    fmt.Println("Value of x:", x)
}

This time the output is:

Value of x: 100

Now the actual value is changed because the function receives a reference (pointer).

Pointer to Struct in Function

You can also pass a pointer to a struct, allowing the function to update its fields.

Example

The following example demonstrates how to use pointers to modify the fields of a struct in a function in Go:

package main
import "fmt"

type Person struct {
    name string
    age  int
}

func updateAge(p *Person, newAge int) {
    p.age = newAge
}

func main() {
    p := Person{name: "Neha", age: 25}
    updateAge(&p, 30)
    fmt.Println("Updated Age:", p.age)
}

When executed, this program outputs:

Updated Age: 30

When Not to Use Pointers

Use pointers only when necessary. For small values like integers or booleans, using value passing is often more readable and sufficient. Pointers are more useful with structs, slices, or when performance or mutability is a concern.

Exercise

Choose the correct answers for the following questions about passing pointers to functions in Go.

  1. What happens when you pass a variable to a function without a pointer?
  2. How do you declare a function that accepts a pointer to an integer?
  3. What does the * operator do in a pointer context?

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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